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.次に、ファイル(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);
      }

     }



 ?>
4

3 に答える 3

4

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";}
于 2011-11-07T11:21:47.007 に答える
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>";
}
于 2011-11-07T11:20:25.727 に答える
1
if (!filter_var('anyurl',FILTER_VALIDATE_URL))
 echo "Wrong url";
end;

http://php.net/manual/en/filter.filters.validate.php

于 2011-11-07T12:06:49.117 に答える