0

I have a php script that reads RSS feed and displays the items on the page:

 <?php
    function getFeed($feed_url) {

         $content = file_get_contents($feed_url);
         $x = new SimpleXmlElement($content);
         $j=0;

         foreach($x->channel->item as $entry) {
              if ($i <5){
                   echo "<li>
                   <a href='$entry->link' title='$entry->title'>" .
                   $entry->title . "</a><br/>
                   <span style='color: 444444;'>".$entry->description."
                   </span>..<a href='$entry->link' title='$entry->title'>
                   <b>more</b></a>
                   </li>";      
              }$i +=1;
         }
    }
    getFeed("http://example.org/feed/");    

    ?>

It works well and displays the RSS item with the links in it. The issue is when the rss feed is down or becomes 0byte size file and it does not show anything. Is there a way to check if the file exists and not empty and make this script fail gracefully way before the server times out?

4

3 回答 3

2

使用卷曲功能:

function getFeed($feed_url) {

    // GET request
    $handle = curl_init($feed_url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($handle);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

    if($httpCode != 200 || empty($response)) {
        echo "feed url not found or missed";
        exit;
    }
    curl_close($handle);

    // also catch error in xml
    try {
        $x = new SimpleXmlElement($response);
    catch (Exception $e){ 
         echo 'XML not valid'; 
         exit; 
    } 
    // rest of function
 }
于 2012-12-17T22:27:28.153 回答
1

失败file_get_contents返回false,您可以检查是否发生错误并退出。

$content = file_get_contents($feed_url);
if (content === false) return;
$x = new SimpleXmlElement($content);
于 2012-12-17T22:34:49.417 回答
0

你可以检查你在 $content 中得到了什么。就像它是空的或者不是以 xml 标头开头的,你就停下来。

于 2012-12-17T22:21:45.390 回答