Easy feed reading with SimplePie

In an earlier article, I discuss a method of displaying WordPress content on pages outside of WordPress. This method gives you access to the complete WordPress API, including the header and footer functions, the loop, comments, and more. Basically anything you can do in a WordPress template, you can do in an external page using this method.

But that’s often overkill. In many cases you just want to display headlines or a single latest post and don't need all this other stuff. Additionally, this method only allows you to display content from a single WordPress site. If you want headlines from more than one site, you’re out of luck.

RSS to the rescue

It’s called Really Simple Syndication for a reason. If you just want content and don't need all the other WordPress functions, RSS is the way to go. You can show headlines and/or content from as many other sites as you want without incurring the overhead of loading the entire WordPress framework, and you can cache the results so that pages loads are nice and quick.

Introducing SimplePie

Admittedly, this is a late introduction. SimplePie has been around for a few years now but it’s not as widely used as it maybe should be. It’s a great way to display external RSS or Atom feeds with a minimum of hassle. At it’s most basic, you can do this with just half a dozen lines of code. Let’s see how.

First, you need to download the SimplePie library. Unzip the file and copy simplepie.inc somewhere accessible to your web site. For this example, we’ll put it in a directory called /inc just inside your site’s DocumentRoot. I rename mine to simplepie.php for consistency with other libraries I use, but that’s not necessary. Here we’ll stick with the default .inc extension.

In this article, I will show how to do four things commonly done with RSS feeds on the web.

  1. Show the five latest headlines
  2. Displaying the full content of the single latest post
  3. How to display two feeds on a single page
  4. Combining headlines from two feeds into a single list

A note about caching

SimplePie provides a great caching mechanism so that feeds don't have to be retrieved on every page load. This requires a writable directory on the server where the feeds can be stored. By default this location is ./cache, meaning a directory called “cache” in the same directory as the file calling simplepie.inc. Be sure your web server can write to this directory, either by changing the permissions, ownership, or some other means, as appropriate for your setup.

The default cache time is one hour. Both this and the cache location are customizable but we’ll be sticking with the defaults here. See the SimplePie API reference for details when you’re ready to dig into this.

Getting started

So here we go. First, load SimplePie by adding this line to the top of the PHP page you’ll be using it on:


<?php 
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/simplepie.inc'; 
?>

Once it’s loaded, we’ll add a second line to create our SimplePie object and give it the location of the RSS or Atom feed we’d like to display:


<?php 
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/simplepie.inc'; 
$feed = new SimplePie('http://feeds.basilandco.com/Cocktailia');
?>

That’s all the prep work we need. Unless otherwise noted, you’ll use this code for all the examples below.

We now have the feed loaded and we can start playing with the contents.

Example One: Display five latest headlines

For this first example we’re simply going to display five recent headlines. A typical use case for this might be a someone who wants to automatically link to their latest blog content on another site or on a non-WordPress page on the same site.

Once the above code is in place, we can start printing out the contents of the feed. First, we’ll probably want to display the title of the feed itself. For a WordPress-based site, this is the same as the blog name.


<h1><?php print $feed->get_title(); ?></h1>

Now let’s get the contents. To do this, we’ll retrieve an array of posts from the SimplePie object and iterate through them.


<h1><?php print $feed->get_title(); ?></h1>
<ul>
<?php foreach ($feed->get_items(0, 5) as $item): ?>
    <li>
        <a href="<?php print $item->get_permalink(); ?>">
        <?php print $item->get_title(); ?></a>
    </li>
<?php endforeach; ?>
</ul>

In the above code, you can see our call to SimplePie’s get_items() method. Call this method without the optional arguments will retrieve the entire feed, or pass arguments to get exactly what you want. The first argument specifies the element to start with. Remember, arrays begin with zero so use 0 here to start with the latest post. The second argument is the number of items you want — we’re using 5 for this example; use 10 if you want a longer list, 1 if you want a single item, or whatever is appropriate for your needs.

That’s it! You’ve now got a list of headlines, linked to the articles on the original site.

Example Two: Display the latest post content

Displaying the latest full post is pretty similar to the above but we’ll be introducing a couple new methods to retrieve a single post and display the post body (“description”, in RSS terminology).


<h1>Latest post from <?php print $feed->get_title(); ?></h1>
<?php $item = $feed->get_item() ?>
<h2><?php print $item->get_title(); ?></h2>
<?php print $item->get_description(); ?>

The interesting thing here is that we’re calling get_item() rather than get_items() (singular instead of plural). By default, this method will return the first item in the feed, which is your most recent post. Add an optional argument of a single integer to specify a different post.

The remaining code is basically the same. We’re using the same method to display the title but have added a call to get_description() for the post body.

Example Three: Show headlines from two feeds

A common use case for SimplePie is to display headlines from a number of sources. Say you’ve got a personal web site that you want to show headlines from the various blogs you write for. Building on what we’ve done so far, this is no problem at all. Let’s see how.

Back up near the beginning of this article, I showed how to include the SimplePie object and instantiate an object for the feed you wish to display. We’re going to make a small change to that code here and also create a second SimplePie object for the new feed we’ll be adding.


<?php 
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/simplepie.inc'; 
$feed1 = new SimplePie('http://feeds.basilandco.com/Cocktailia');
$feed2 = new SimplePie('http://feeds.basilandco.com/CocktailCamp');
?>

So now we’ve got $feed1 and $feed2, two SimplePie objects for our two feeds. From here you just follow the five latest headlines instructions above, but using that block twice on your page, using the two different feed variables we’ve created here.


<!-- First feed - note use of "feed1" -->
<h1><?php print $feed1->get_title(); ?></h1>
<ul>
<?php foreach ($feed1->get_items(0, 5) as $item): ?>
    <li>
        <a href="<?php print $item->get_permalink(); ?>">
        <?php print $item->get_title(); ?></a>
    </li>
<?php endforeach; ?>
</ul>

<!-- Second feed - note use of "feed2" -->
<h1><?php print $feed2->get_title(); ?></h1>
<ul>
<?php foreach ($feed2->get_items(0, 5) as $item): ?>
    <li>
        <a href="<?php print $item->get_permalink(); ?>">
        <?php print $item->get_title(); ?></a>
    </li>
<?php endforeach; ?>
</ul>

Example Four: Combine headlines from multiple feeds

For our final example, we’re going to combine headlines from two feeds into a single list. You might do this if you’ve got multiple feeds on a similar topic or if you’re aggregating content from multiple writers. Once again, we’ll be changing how we instantiate our SimplePie object, this time passing an array of URLs instead of a single one.


<?php 
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/simplepie.inc'; 
$feeds = new SimplePie(array(
    'http://feeds.basilandco.com/Cocktailia',
    'http://feeds.basilandco.com/CocktailCamp'
));
?>

This results in a single object containing data from two feeds, instead of one object for each individual feed. Now we can display them as usual.


<ul>
<?php foreach ($feeds->get_items(0, 10) as $item): ?>
    <li>
        <a href="<?php print $item->get_permalink(); ?>">
        <?php print $item->get_title(); ?></a>
    </li>
<?php endforeach; ?>
</ul>

You won’t use get_title() here, as there is no one single title for multiple feeds. You also may want to increase the number of headlines you’re showing so you get a good sample from each feed. Note that these are displayed in date order so you may have an uneven number of posts from each.

Further reading

These examples are intentionally basic but they should cover the most common use cases for SimplePie. Once you’ve tried these things and familiarized yourself with how it works, your next stop should be the SimplePie web site itself, where they've got some very good documentation, a complete API reference, and lots of examples. Have fun!

What is a corvid?

Corvidae is the family of birds that contains crows, ravens, magpies, and jays, among others. Widely considered to be the most intelligent of the birds, they live in complex social groups and take part in elaborate games. Various members of the corvid family have demonstrated self-awareness, the ability to memorize, and they are even known to create and use simple tools.

Found nearly everywhere on Earth, corvids have played an important role in art, literature, and mythology throughout history.