Let’s say we have a university website running on a CMS and a couple of student blogs running on a blogging tool like WPMU. Then on the university website homepage we need to pull several latest blog teasers from the student blogs. We can accomplish this quite easily with a free PHP class called SimplePie. What the library does is it fetches the blog RSS or Atom feed that we provide and parses it into an easy to use formatted data.
require_once('simplepie.inc'); $webfeed = "http://mywordpressblog.com/index.php?feed=rss2"; $feed = new SimplePie(); $feed->set_feed_url($webfeed); // $feed->set_cache_location("./cache_folder"); //set your own cache folder; default ./cache // $feed->set_cache_duration(1800); //cache duration in number of minutes; default 3600 $feed->init(); $feed->handle_content_type(); echo '<ul>'; foreach ($feed->get_items(0, 3) as $key => $item) { echo '<li>'; echo '<a href="'. $item->get_permalink() .'">'. $item->get_title() .'</a>'; echo '</li>'; // $item->get_description() to get the teaser // $item->get_date('F jS, Y') to get the date formatted using php date() } echo '</ul>';
A thing to note here is the foreach loop in line 13 controls how many items you would like to retrieve from the feed. In the example above, it’s set to read three feed items (stated as 3) starting from the first item (stated as 0).
One of the advantages of using SimplePie is performance. SimplePie is configured to grab and cache the feed so that the server doesn’t have to fetch them every time the webpage is loaded. By default, SimplePie stores its cache in a directory called “cache” with a cache duration of an hour. So it’s advisable to create this directory with a correct permission assigned in advance. These default settings can be overridden very easily.
Besides standalone code, you can also find a handful of SimplePie plugins that were built for major CMS such as Joomla! or Drupal. With web feeds becoming quite common today, you can use SimplePie in many creative ways for instance to fetch Tweets, Flickr photos or cool products from eBay.