检查 URL 是否有效以及在 PHP 中检查有效的 XML。

3

我想要阅读一个RSS源并将其存储。为此,我正在使用:

<?php
$homepage = file_get_contents('http://www.forbes.com/news/index.xml');
 $xml = simplexml_load_string($homepage);
 echo '<pre>';
 print_r($xml);
 ?>

但首先,我想检查一下:
1. URL 是否有效,即它的响应时间是否正常。
   $homepage = file_get_contents('http://www.forbes.com/news/index.xml');

时间少于1分钟,并且url地址正确。

2.然后检查File(http://www.forbes.com/news/index.xml)是否有有效的XML数据。 如果是有效的XML,则显示响应时间,否则显示错误。

我的问题的答案:

感谢大家的帮助和建议。我解决了这个问题。为此,我编写了以下代码:

  <?php
 // function() for valid XML or not
 function XmlIsWellFormed($xmlContent, $message) {
libxml_use_internal_errors(true);

$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xmlContent);

$errors = libxml_get_errors();
if (empty($errors))
{
    return true;
}

$error = $errors[ 0 ];
if ($error->level < 3)
{
    return true;
}

$lines = explode("r", $xmlContent);
$line = $lines[($error->line)-1];

$message = $error->message . ' at line ' . $error->line . ': ' . htmlentities($line);

return false;
 }
   //function() for checking URL is valid or not
  function Visit($url){
   $agent = $ch=curl_init();
   curl_setopt ($ch, CURLOPT_URL,$url );
   curl_setopt($ch, CURLOPT_USERAGENT, $agent);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt ($ch,CURLOPT_VERBOSE,false);
   curl_setopt($ch, CURLOPT_TIMEOUT, 60);
   curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch,CURLOPT_SSLVERSION,3);
   curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
   $page=curl_exec($ch);
   //echo curl_error($ch);
   $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
   curl_close($ch);
   if($httpcode>=200 && $httpcode<300) return true;
   else return false;
  }
         $url='http://www.forbes.com/news/index.xml';
         if (Visit($url)){
   $xmlContent = file_get_contents($url);

      $errorMessage = '';
      if (XmlIsWellFormed($xmlContent, $errorMessage)) {
      echo 'xml is valid';
        $xml = simplexml_load_string($xmlContent);
        echo '<pre>';
        print_r($xml);
      }

     }



 ?>
3个回答

5
如果 URL 无效,file_get_contents 将会失败。
要检查 XML 是否有效,请:
simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))

如果它是真的,那么它将返回true;如果不是,它将完全失败。

 if(simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))){

        echo "yeah";
    }else { echo "nah";}

1

这个页面包含一个使用正则表达式验证URL的代码片段。函数和用法:

function isValidURL($url)
{
     return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

if(!isValidURL($fldbanner_url))
{
    $errMsg .= "* Please enter valid URL including http://<br>";
}

1

请注意,该函数只会将ASCII URL视为有效;包含非ASCII字符的国际化域名将失败。 - omnath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接