Taking RSS to the next level with Simplepie

Newsfeed and RSS

In an attempt to improve performance and also consolidate some of this blog’s functionality I have been busy decommissioning a few plugins. As I have mentioned previously WordPress Plugins are excellent value and potentially give one’s blog that little bit of extra pizzazz.

The self hosted blog of course, has the added advantage of being able to install and run the full collection of plugins as opposed to a hosted blog which has only a limited choice available.

Warning: there’s no point in reading any further if you don’t know what RSS or a Newsreader are. If you are a blogging enthusiast then you might just find this post of interest.

Well, one of the plugins that hit the bucket this weekend was KB Advanced RSS Widget. An excellent choice if you are wanting to take RSS feeds within your WordPress blog to the next level:

WordPress comes with a default RSS widget, but you get no control over how the feed shows up in your sidebar. Want more control? The KB Advanced RSS widget gives it to you. With it, you can:

  • Decide which RSS fields to display (as opposed to the default RSS widget, which limits you to link, title, and description);
  • Decide how to format the fields (it doesn’t have to be a list if you don’t want it to be);

Be aware that it’s called “advanced” for a reason. You need to know some HTML to use this fully. Also, please note that this is a widget, so you need to be using a widgets-enabled theme.

The above plugin served me well, came with good doco and was also well supported by the developer through the WordPress versions. But in order to consolidate, get rid of some plugins and therefore move the functionality (which I did not want to loose) deeper down I had to learn a little bit about SimplePie. (No it’s not a some type of shortbread pastry!).

The SimplePie library is built into WordPress and it’s associated functions available to those that wish to delve. Here’s a summary of what SimplePie is and what it can do for the avid blogger:

  • A code library, written in PHP, intended to make it ridiculously easy for people to manage RSS and Atom feeds.
  • An easy to use API that handles all of the dirty work when it comes to fetching, caching, parsing, normalizing data structures between RSS and Atom formats, handling character encoding translation, and sanitizing the resulting data.
  • Free (i.e. no cost) open-source software, with a license more liberal than the GPL (BSD-licensed), that was built and improved over the course of years by people who have a passion for good software that makes people’s lives easier.
  • Well documented with a complete API reference, tutorials and screencasts for popularly requested uses, and details about the inner workings of the library.
  • Always looking for more people to contribute to the project in terms of code, patches, support, and evangelism.
  • A solution where we’ve worked very hard to keep the bar as low as possible for people who want to use it, but at the same time you MUST have a fundamental grasp of the PHP language. If you don’t know PHP, and are interested in getting a handle on the basics, we recommend PHP 101: PHP For the Absolute Beginner (begin with parts 1-3, then move onto parts 4-7 making sure you actually *understand* them).

Let’s start with a simple example.

Here’s a screenshot of the feed as it appears at the bottom of most pages of this blog.

Snapshot of the AmidhaBuddha RSS feed

So what is the advantage of using SimplePie to display feeds? As opposed to just using the standard RSS Widget I hear you ask! Control baby – control! The little favicon that’s displayed within the text area in the “Tingting” widget cannot be done with a standard RSS Widget – this is where SimplePie comes into it’s element. The ability to tailor what’s displayed from the feed and how it’s displayed on the screen are endless. (Next on my SimplePie to-do-list agenda is to merge the contents of various feeds together and display them in the one widget – or even on a page).

Give me the code man!

OK-OK… in order to display this feed we need to drop the following code into a PHP enabled widget – just like the standard Text Widget but only “crunchier” (is able to execute PHP, HTML and various other scripts in addition to plain old text). The plugin I use to provide this blog with PHP enabled widgets is called Executable PHP widget and is highly recommended.

Note: the code below should be sufficiently commented for you to be able to follow what is going on and perhaps even adapt it for your own blog. If you hover over the text a little toolbar will appear and give you an option to copy the code.

<?php
/*
Snippet Name: Fetch AmidaBuddha
Snippet URI: http://www.trupela.com/
Description: retrieve and format feed items using SimplePie.
Version: 0.1
Author: Robert Schilt
Author URI: http://www.trupela.com/

*/

// Include access to to SimplePie functions
include_once(ABSPATH . WPINC . '/feed.php');

// Get the feed for URL...
$rss = fetch_feed("http://www.amidabuddha.org/news.xml");

// Lets work on the feed we just fetched
if ( $rss && !is_wp_error( $rss ) ) { // Do not proceed if NULL or error on fetch
	$maxitems = $rss->get_item_quantity(1); // How many #items? (1=most recent)
	$rss_items = $rss->get_items(0, $maxitems); // Move #item(s) to array
	if ($maxitems == 0) { break; } // No point proceeding if zero #items
	else {
		// Prcoess each item starting with most recent
		$display_this = '<ul id="rss_amidabuddha">'; // Start List | Use CSS to format
		// Process each item
		foreach ( $rss_items as $item ) {
			// Format Author's name (just in case we need it)
			$author = $item->get_author();
			if ( is_object($author) ) {
				$author = $author->get_name();
				$author = esc_html( strip_tags( $author ) );
			} // endif
			else {
				$author = 'Anon';
			} // endelse
			// Start list item | CSS format | Favicon
			$display_this .=  '<li class="nobullet"><a title="Amidabuddha RSS" rel="nofollow" href="http://www.amidabuddha.org/news.xml"><img src="http://www.trupela.com/wp-includes/images/favicons/amidabuddha.ico" width="24" height="24" alt="Amidabuddha" /></a>&nbsp;';
			$remove = array("..."); // Remove these strings from from item content
			// Cleanup the content | Remove string(s) || Show 1st 200 characters | Throw a 'read more' link on to the end
			$display_this .= substr(str_replace($remove,"",wp_kses($item->get_content(),array())),0,200) . '[<a rel="nofollow" title="Read the rest of this tingting" href="http://www.amidabuddha.org/">...</a>]</li>';
			// End list item
		} // endforeach
		// Close List and Show
		$display_this .= '</ul>';
		echo $display_this;
	} // endelse
} // endif
/* Fingers crossed and hope for the best */
?>

The Author

8 responses to “Taking RSS to the next level with Simplepie”

  1. Posts about Open Source Software as of October 11, 2009

    [...] of October 11, 2009 October 11th, 2009 by admin | Filed under Open Source Software. Taking RSS to the next level with Simplepie – trupela.com 10/12/2009 In an attempt to improve performance and also consolidate some of [...]

  2. Webby Scripts Taking RSS to the next level with Simplepie

    [...] this article: Taking RSS to the next level with Simplepie [...]

  3. Steve Byde

    Hi there

    Got your Taking RSS to the next level with Simplepie code working. Almost got what I want but now at bit of a loss. Basically have a chart rss feed but want to strip out and display image, song title and artist name only. Is there a way of seeing tags of a feed and the say $remove tag name?

    This would help no end.

    Many thanks

  4. John

    Hey mate i am the it manager of the sportnooz.gr site in Greece…I am trying to fix a multi rss widget taking informations from 5 other sites with the favicon.ico images in the begging of each line.How can i do that with your code?iis it possible?
    Best regards

Leave a Reply

House rules: you are more than welcome to leave a comment but as the author and the person ultimately responsible for published content - I reserve the right to moderate all comments. Note that all fields marked with an asterisk must be filled out.

Notify me of followup comments via e-mail.