Tues, 1 Jan 2008 19:48:00 EST
Using PHP to Parse and Display an RSS Feed
Just thought I'd share a little PHP script that I wrote recently which takes an RSS feed, parses it and echoes it out on a page. The code itself is very simple and based on PHP5's simplexml_load_file function. The first section of code takes a predefined RSS feed, $feed, and loads the feed's XML into the variable $xml via the simplexml_load_file function. I've also added an @ in front of the function to suppress the long list of warnings and errors produced by a feed that fails to load. I then check to see that something has, in fact, been loaded into $xml, then begin loading the feed data. Accessing an individual element within an XML document is just as easy as loading the document itself. To access an element in the document, you simply write out the path of the element with each level of the tree separated by "–>". For example, $site = $xml->channel[0]->title[0]; will load the title of the news feed into the variable $site. Check out the code and live demo below. This example takes the BBC World News front page RSS and echoes the channel information and the first 20 feed items.I'm currently working on a Netvibes-style application that is based off of the use of this function. Check back in a few weeks when I'll be sharing a much more in depth version of the RSS reader.
View a Live Demo »
<?php
$feed = '<Insert Feed URL>';
$xml = @simplexml_load_file($feed);
if($xml) {
$siteTitle = $xml->channel[0]->title[0];
$siteLink = $xml->channel[0]->link[0];
$siteDesc = $xml->channel[0]->description[0];
echo "<strong>$siteTitle<br/>
<a href=\"$siteLink\">
$siteLink
</a>
<br/>$siteDesc</strong><br/><br/>";
for($i=0; $i<20; $i++) {
$itemTitle = $xml->channel[0]->item[$i]->title[0];
$itemLink = $xml->channel[0]->item[$i]->link[0];
$itemDesc = $xml->channel[0]->item[$i]->description[0];
echo "$itemTitle<br/>
<a href=\"$itemLink\">
$itemLink
</a>
<br/>$itemDesc<br/><br/>";
}
} else {
echo "ERROR: Failed to open stream";
}
?>
















6 Comments So Far