• How to Read an RSS Feed with PHP 5

    0
    scissors
    April 22nd, 2009PaulUncategorized

    PHP 5’s ability to read XML files is fantastically easy to use. In the past it was possible but it required quite a bit of long winded code to get any where. PHP 5’s SimpleXmlElement function makes working with XML a breeze, and with much less code too! Let’s take the following example:

    $feed = file_get_contents(’http://www.mywebsite.com/rss/’);

    $rss = new SimpleXmlElement($feed);

    foreach($rss->channel->item as $entry) {
       echo “<p><a href=’$entry->link’ title=’$entry->title’>” . $entry->title . “</a></p>”;
    }

    In the above example we want to display the contents of an RSS feed, in our example http://www.mywebsite.com/rss/. Using the file_get_contents function we can get the contents of this RSS file and put them in a variable called $feed. We then use the SimpleXmlElement function to process the RSS feed and put it in a format we can use. This usable format (now an objext) is stored in $rss.

    The $rss object can now be used to get any information that was in our RSS feed. The foreach loop does just that, looping through each item

    • Share/Save/Bookmark
    • Share/Save/Bookmark




Leave a Reply

Clickcha - The One-click Captcha