Advertisement

Extending SimplePie to Parse Unique RSS Feeds

by

A few days ago, as I prepared our Create a Slick Flickr Gallery with SimplePie tutorial, it occurred to me that we haven't posted many articles that covered SimplePie. Considering how fantastic a library it is, I think it's time to take a closer look.

We'll be looking at a more advanced feature that allows you to extend the built-in item class to allow for the parsing of complicated RSS feeds.

Our Mission

If your only desire is to import the feeds of a few blogs to display on your website, you shouldn't have any trouble at all. In fact, the SimplePie.org website has a great intro screencast that will teach you exactly how to do as much. If you're unfamiliar, I highly recommend that you view it. However, from time to time, you'll come across some unique tag names. For example, while working on my personal site reboot, I determined that I'd like to display my nettuts+ videos from Blip.tv's RSS feed. Upon reviewing the feed itself, I came across tags, like: <blip:smallThumbnail>.

Now SimplePie does a tremendous job of simplifying the most common procedures. But obviously, they can't be expected to provide convenient short-cut methods for every namespace, now can they!? Of course not. I decided that this would make for an excellent screencast. So, I've created a simple example that will pull in all of the nettuts+ screencasts, and allow the for a "pop-up" video when the user chooses one.

finished product
with video

It's a simple enough layout; but should be just perfect for demonstration purposes. Without further ado, let's begin.

Step 1: Index.php

The first step is to download SimplePie and place the "simplepie.inc" file in your "includes" folder. Next, create index.php'. Within it, paste the following basic code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/default.css" />
<title>Untitled Document</title>
</head>

<body>

<div id="container">
</div><!--end container-->


<!-- begin scripts -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

<script type="text/javascript">
</script>

</body>
</html>

The only things worth noting are that we've created a wrapping "container" div, and are using Google's CDN to import jQuery. Don't worry if you're not familiar with this library; it's just a way to add a bit of frosting at the end. It's hardly essential.

Step 2: New SimplePie();

I'll be assuming that you have a basic understanding of SimplePie. If you don't, watch their introductory video first, and then return. Fortunately, there's nothing too difficult here.

Just before your doctype, add a bit of PHP.

<?php

require 'includes/simplepie.inc';
$feed = new SimplePie();
$feed->set_feed_url('feed://nettuts.blip.tv/rss');
$feed->set_item_class();
$feed->enable_cache(true);
$feed->set_cache_duration(3600);
$feed->set_cache_location('cache');
$feed->init();
$feed->handle_content_type();

?>

The first step when working with SimplePie is to create a new instance of the SimplePie class. Next, we naturally need to tell it the url of our feed (set_feed_url).

RSS Link

As I mentioned earlier, we'll be working with Blip.tv today. If you have your own account, click on one of your videos to visit the show page. Next, scroll down to the bottom. You'll see an RSS link within the footer. Copy that url and paste it in as a parameter.

RSS

Next, we need to set an item_class. We'll modify this section a bit later. The next three methods set up caching, the duration (in seconds), and the location of our "cache" folder. We better create that right now. Make sure that your folder structure looks similar to this.

folder structure

$feed->init();

Finally, we need to initialize everything. If you don't understand this, don't worry about it too much. Just accept that it's what "gets the feed rolling".

"Init() is what makes everything happen. Period. This is where all of the configuration options get processed, feeds are fetched, cached, and parsed, and all of that other good stuff. This is called automatically if you pass a URL to the SimplePie constructor." - SimplePie Documentation

Step 3: Grabbing the Title and Description

title and description

Let's write a bit of code that will extract the title and description from our feed. Within the container div, append the following two lines.

<h1><?php echo $feed->get_title(); ?></h1>
<p><?php echo $feed->get_description(); ?></p>

Notice those easy to understand methods?! SimplePie makes these procedures a cinch. We created the $feed object at the top of our page. Remember, it's essentially a copy of the item class. To access the methods, we need to use an OOP approach. For a full list, be sure to visit SimplePie's API reference.

For the title, we're using "$feed->get_title()", and for the description, we'll conveniently use "$feed->get_description".

Step 4: The Loop

The next step is to loop through all of the items in the RSS feed.

<?php foreach($feed->get_items() as $item) : ?>
	
	<div class="entry">
		<a href="" title="">
			<img src="" alt="<?php $item->get_title(); ?>" />
		</a>
	</div>
<?php endforeach; ?>

Lots of PHP here, but it's all relatively simple. We're using the shorthand form of a PHP loop. SimplePie supplies a "get_items()" method that will retrieve every item from the RSS feed. We then loop through each item and assign a temporary variable called $item. We can now use this new variable to retrieve specific information at the item level.

Problem

We've unfortunately hit a snag. If you'll refer back to the demo, you'll see that we want to pull in a thumbnail for each item. If we visit the url of the RSS feed, and then choose "View Source", we'll see the following: <blip:thumbnail_src>NETTUTS-WordPressForDesigners8774-306.jpg</blip:thumbnail_src>

So what do we do when SimplePie doesn't recognize a unique namespace like "blip"? The solution is to create a new class that extends the SimplePie item class.

New Class

Return to your "includes" folder and add a new file called: simplepie_blip.inc

Don't worry if you're not familiar with that file extension. We'll just be using PHP. We need a way to reference that "blip" namespace. Return to the RSS feed and once again view the source. Scroll to the top and look for something like this:

blip

Copy this value into your clipboard. Next, paste the following code into your new .inc file.

<?php

define("SIMPLE_NAMESPACE_BLIP", "http://blip.tv/dtd/blip/1.0");

class SimplePie_Item_Blip extends SimplePie_Item 
{
...
}

It's Just a Class

All we're building here is a very simple class that extends the SimplePie item class. At the top of our code, we define a constant and make it equal to the url that you just copied. We next create a new class - the name can be whatever you want. It's vital that you make sure you write "extends SimplePie_Item". This will give us access to the necessary properties and methods from the parent class.

What Do We Want?

Let's first figure out what values we need to retrieve. Take another look at the RSS feed source code.

source code

For this simple(r) tutorial, we'll only grab three tags.

  • <blip:thumbnail_src> : contains the name of our thumbnail image.
  • <blip:embedLookup> : contains the url that will allow us to embed the video on our page.
  • <blip:puredescription> : contains the description of the video.

Let's start by creating our thumbnail_src method. Create a new method within the Class braces.

function get_thumbnail_src() 
{
	$data = $this->get_item_tags(SIMPLE_NAMESPACE_BLIP, 'thumbnail_src');
	return $data[0]['data'];
}

You're free to name the method whatever you like; just make sure that it's easy to understand. We begin by creating a new variable called $data. SimplePie offers a method called "get_item_tags". Remember, we're able to use this because we're EXTENDING the item class. Within the parenthesis, we paste in our constant "SIMPLE_NAMESPACE_BLIP", and then add the name of the tag that we're searching for. In this case, we want the "<blip:thumbnail_src>" tag.

What to Return?

It's a bit difficult to describe the array that we'll be returned. I recommend that you review the screencast to gain a better understanding. For the sake of simplicity, just accept that, in order to access the exact value, we must find [0]['data'] within our $data array.

That's actually all that is required. We can now begin using "get_thumbnail_src()" in the same way that we would "get_title()". Let's return to index.php and add this new method.

Find the image tag within the .entry div.

 
<div class="entry">
	<a href="" title="">
		<img src="" alt="<?php $item->get_title(); ?>" />
	</a>
</div>

get_thumbnail_src()

When we call our "get_thumbnail_src()" method, it will return the filename, i.e. "NETTUTS-WordPressForDesigners8774-306.jpg". This is just the name of the image; we still need the full path. Luckily, this is easy. All Blip images will be stored here: "http://a.images.blip.tv/{filename}".

Within the source attribute of our image, add:

<img src="http://a.images.blip.tv/<?php echo $item->get_thumbnail_src(); ?>" alt="<?php $item->get_title(); ?>" />

See how easy it was to use our custom method? Now, let's return to our extended class file and create the other two methods. I won't go over these, because they follow the exact same path.

// end get_thumbnail_src function.

function get_pure_description() 
{
	$data = $this->get_item_tags(SIMPLE_NAMESPACE_BLIP, 'puredescription');
	return $data[0]['data'];		
}

function get_embed_id()
{
	$data = $this->get_item_tags(SIMPLE_NAMESPACE_BLIP, 'embedLookup');
	return $data[0]['data'];
}

It's important to remember that the "puredescription", and "embedLookup" tags are case sensitive. It's easiest if you just copy the text directly from the source of the RSS feed.

See if you can place these methods in their proper places on your own. As a refresher, the returned values of our methods should look like:

  • get_thumbnail_src() : NETTUTS-WordPressForDesigners8774-306.jpg
  • get_pure_description() : "This is a video that will teach bla bla..."
  • get_embed_id : grg378cLj7EM

After inserting these methods, you should end up with something that looks like the following:

<div class="entry">
	<a href="http://blip.tv/play/<?php echo $item->get_embed_id();?>" title="<?php echo $item->get_pure_description();?>">
		<img src="http://a.images.blip.tv/<?php echo $item->get_thumbnail_src(); ?>" alt="<?php $item->get_title(); ?>" />
	</a>
</div>

Hopefully, all of this makes sense. If not, review the screencast. At this point, your page should resemble this:

no css

Step 5: CSS

Not too pretty, eh? Let's add an ounce of CSS. These styles don't relate to the tutorial in any way. Considering this, I won't detail each property. You're free to review the CSS file here. It's very minimalistic.

finished css

Step 6: jQuery

Just to have a bit of fun, I decided that, when the user clicks on one of the images, a pop-up video player should appear. Let's use jQuery to allow for this functionality.

	$('.entry a').click(function() {
		var url = this.href;
		var embedString = '<embed src="' + url + '" type="application/x-shockwave-flash" width="640" height="480" allowscriptaccess="always" allowfullscreen="true"></embed>';
		
		$('<div id="video">')
		  .append(embedString)
		  .append('<p>X</p>')
		  .css({
		  	left: $(window).width() / 2 - 320,
			top: '50px' })
		  .appendTo('body')
		  .children('p').click(function() { $(this).parent().remove(); });
		  
		  return false;
	});

Analysis

$('.entry a').click(function() {

When the anchor tag within our .entry div is clicked, run a function.

var url = this.href;
var embedString = '<embed src="' + url + '" type="application/x-shockwave-flash" width="640" height="480" allowscriptaccess="always" allowfullscreen="true"></embed>';

Create a variable called "url" and make it equal to the href of the anchor tag that was clicked. Remember, this href links contains the embed link. Next, create the embed tag. Truthfully, we could do something a bit more efficient here. This is the code that blip.tv provides, so it will suffice for now. You might want to look into something that's a bit more "validator" friendly in the future.

$('<div id="video">')
  .append(embedString)
  .append('<p>X</p>')
  .css({
	left: $(window).width() / 2 - 320,
	top: '50px' })
  .appendTo('body')
  .children('p').click(function() { $(this).parent().remove(); });
  • Create a new div element.
  • Insert the embed tag that we just created (represented by the "embedString" variable.).
  • Add a paragraph tag containing the letter X. This will allow the user to exit out of the video.
  • Set the positioning of our video. This code just makes sure that it's centered within the container div.
  • Append our new div element to the body tag. It won't show up at the bottom of the page because we've used CSS to position it absolutely. Review the CSS file for more info.
  • Find that P tag - which contains the letter "X". When that element is clicked, find the #video element and remove it from the page. This is the code that gets rid of the video.

Complete

Run the page in your browser, click on an image, and you'll find that the video pops up perfectly. If the user has Javascript disabled, he or she will simply be directed to a new page that contains the embedded video.

I hope this helped you to gain a better understanding of SimplePie's capabilities. Have a great weekend...but not before Digging this tutorial. :)

with video
  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Advertisement