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?

3 Answers 3

2

use curl function:

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
 }
Sign up to request clarification or add additional context in comments.

Comments

1

On failure file_get_contents returns false, you can check if an error happened and exit.

$content = file_get_contents($feed_url);
if (content === false) return;
$x = new SimpleXmlElement($content);

Comments

0

You could check what you get in $content. Like if it is empty or doesn't start with a xml header you just stop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.