This tutorial shows you how to use the SimplePie PHP library to display an RSS or Atom feed in under 10 lines of code.
DOWNLOAD THE SOURCE CODE
Syndication feeds are a simple and popular way of listing the contents of a site. The differences in formats, namely RSS and Atom, can be a headache for developers, but libraries like SimplePie can be used to provide a consistent interface to the underlying formats. This tutorial will look at creating a simple feed reader in PHP, using the SimplePie library.
You can download the SimplePie library for free from here. This tutorial uses version SimplePie 1.2.
The SimplePie library code is located in a file called simplepie.inc. You have two options where you place this code: either you extract it to a folder separate from your project, and reference it from the PHP.INI file, or you simply copy the simplepie.inc file to the same location as your PHP source code.
For simplicity I choose to copy the simplepie.inc file to my projects source code directory, as you can see in the screenshot below.
In your PHP code include a reference to the simplepie.inc file.
require_once('simplepie.inc');
The following 3 lines of code create a new SimplePie object, set the feed URL, and open the feed with the init function.
$feed = new SimplePie();
$feed->set_feed_url('http://www.brighthub.com/hubfolio/matthew-casperson/articles/rss.aspx?ArticleType=3');
$feed->init();
At this point the feed has been loaded and parsed, so all that is left is to display the results. The code below loops through the individual feed items, displaying the title as a link, and then displaying the feed content.
foreach($feed->get_items() as $item)
{
echo '<p><a href="' . $item->get_link() . '">' . $item->get_title() . '</a></p>';
echo '<p>' . $item->get_content() . '</p>';
}
And there you have it - an RSS or Atom feed reader in PHP, using only 9 lines of code.
If you want some more information on the SimplePie library, their website has links to a number of videos, articles and samples that show off some of the more advanced features of SimplePie.
Return to the Tutorial Index