Friday 18 April 2008

Reading RSS (XML) feeds in PHP5 - Part 1

Another new addition to the website, is the reading in of RSS feeds from my blogs. This seemed much harder than it actually was, especially was I got my head around the built in PHP5 XML functions. In essence, you just call @simplexml_load_file("the_xml_url") and the loop over each entry. The hardest part is working out what the section names are within the xml file, and you can just load the XML into a text editor to find out. The code I am using goes as follows:


function doSimpleShowBlog($blogURL) {
// get rss feed contents
$library = @simplexml_load_file($blogURL);
// loop over each entry
foreach ($library->entry as $entry) {
echo "<p>";
echo "Title: ".$entry->title."<br />\n";
echo "Published: ".$entry->published."</p>\n";
echo "<div>".$entry->content."</div>\n";
}
}

Simple huh! Some error checking and so on is recommended but this works for me. An example can be found here.

No comments: