Bright Hub
 
Matthew Casperson's Hubfolio

Displaying RSS or Atom feeds in PHP with under 10 lines of code

Article by Matthew Casperson (227,413 pts )
Published on Nov 10, 2009

This tutorial shows you how to use the SimplePie PHP library to display an RSS or Atom feed in under 10 lines of code.

Introduction

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.

SimplePie PHP Screenshot

Step 1 - Download SimplePie

You can download the SimplePie library for free from here. This tutorial uses version SimplePie 1.2.

Step 2 - simplepie.inc

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.

SimplePie PHP Screenshot

Step 3 - Include simplepie.inc

In your PHP code include a reference to the simplepie.inc file.

require_once('simplepie.inc');

Step 4 - Open a feed

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();

Step 5 - Display the results

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>';

}

Conclusion

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

Search More About:

 
Follow Matthew Casperson
Receive weekly updates from Matthew Casperson
 
Bright Hub - Science & Technology Articles, Buyer's Guides, How-To Tips and Software Reviews
About Bright Hub | Contact Us | Advertise with Us | Become a Writer | RSS | Site Map | Terms of Use | Privacy Policy | Copyright Policy
©2010 Bright Hub Inc. All rights reserved. Page copy protected against web site content infringement by Copyscape