Reading RSS with PHP

Use only the pieces of the Flickr RSS feed that you need

Displaying Photos from Your Flickr Page on Your Website

The Problem
The Internet seems to be getting easier everyday. With sites like Myspace, Flickr, YouTube, and Twitter, you can essentially create a full-on interactive web experience for free and with no knowledge of web design. This is great, but it limits your creativity, and it also requires your readers to remember multiple separate URLs.

On the flipside, you could reverse engineer all of these tools and create your own versions of them for use on your personal website, creating the same immersive user experience you get from using social tools, but that's a good deal of time and effort. The learning experience of building such tools is great, but we don't always have hundreds of hours to dedicate to rebuilding Flickr's robust photo management. Besides, doesn't it seem a little silly to reinvent the wheel?

So, what we're hoping for is a way to get the best of both worlds: how can we utilize the power of Flickr on our own website without needing to dedicate a great deal of time to solving the problem?

The Solution
One solution is to use RSS feeds to grab the content off of our various social media sites (in this example, we'll use Flickr). This way, we don't have to create any content at all. We simply need to grab the content from our account, figure out how to read it right into our website, and then display it in such a way that it will mesh with the rest of our site's design.

In this tutorial, we'll build a PHP class to load and parse a Flickr RSS feed, isolate the pieces of information we need, and output formatted XHTML to the browser. When we're done, it should look like this demo Flickr module.

Necessary Tools and Skills
I'm assuming for the purposes of this tutorial that you have a Flickr account, a basic understanding of PHP 5, and a good grasp on XHTML and CSS. You'll also need a server that supports PHP 5.

Collect the Pieces
Our first step is to find the RSS feed for our Flickr page. The feed is located at the bottom of the main photostream, and it looks like this:

RSS Feed Location on a User Profile

You'll more than likely want to use the "Latest" option. After you click it, you'll get your browsers default RSS feed display, probably offering options to subscribe using a number of services. This is not what we're worried about, though. We want the URL of this page, which should look something like this:

http://api.flickr.com/services/feeds/photos_public.gne?id=22352410@N07&lang=en-us&format=rss_200

In a moment we'll use this URL to load our Flickr page into our website. But first, we need to tell our site how to handle this information.

Creating the Class
We start by creating a file named flickr.php and declaring the class flickr to contain all of our code:

<?php
  class flickr {

  }
?>

Now that we have our class, we need to declare all of the variables we're going to need. Because this is a pretty simple class, we only need one:

  var $feed;

The variable $feed will hold the URL of the Flickr page we're loading.

Next, we'll create a constructor for the class. This is the function that runs when the class is first instantiated. We'll use that to assign the feed URL to the class instance to allow our code to load the proper feed.

  function flickr($feed) {
    $this->feed = $feed;
  }

Now we have a class that has the address of our Flickr feed. Pretty simple so far, right?

Getting Our Information from the Feed
Here's where it starts getting a little tricky. Now we need to load that URL and parse it to extract the relevant information. To do this, we'll create a new function, parse:

  function parse() {
    $rss = simplexml_load_file($this->feed);
    $photodisp = array();
    foreach ($rss->channel->item as $item) {
      $link   = (string) $item->link; // Link to this photo
      $title = (string) $item->title; // Title of this photo
      $media  = $item->children('http://search.yahoo.com/mrss/');
      $thumb  = $media->thumbnail->attributes();
      $url    = (string) $thumb['url']; // URL of the thumbnail
      $width  = (string) $thumb['width']; // Width of the thumbnail
      $height = (string) $thumb['height']; // Height of the thumbnail

      $photodisp[] = <<<________________EOD

          <div class="flickr_photo">
            <a href="{$link}">
              <img src="{$url}"
                width="{$width}"
                height="{$height}"
                title="{$title}"
                alt="{$title}"
                style="border:0;" />
            </a>
          </div>
________________EOD;
    }

    return $photodisp;
  }

In order to pull down the information from this feed, we'll take advantage of the SimpleXML extension that was introduced in the release of PHP 5. To read more in-depth about this useful tool, there is a great article about SimpleXML on the Zend network.

In line 02, we load the feed from Flickr using the SimpleXML extension and place it in the variable $rss. This allows us to then extract data from the feed.

Line 03 creates the variable $photodisp, which is an array to hold each photo as we pull it out of the database.

In line 04, we start a foreach loop to break the feed into individual photos for processing.

Lines 05-11 load pieces of information from the feed into variable for use as we see fit. For the purposes of this class, we grab the URL for the photo's display page, the name of the photo, the location of the thumbnail image, and the thumbnail's width and height.

(Note: lines 07 and 08 load variables that we don't use for display; this is because the Flickr feed uses XML namespaces. These are a useful, albeit confusing, XML convention that helps prevent ambiguity of separate elements for easier reading. Our code is accessing the namespace contained in http://search.yahoo.com/mrss/ and identifying the thumbnail's URL, width, and height.)

Finally, in lines 14-26, we use the heredoc syntax to produce a formatted string of HTML that not only works well with CSS, but also looks great as source code (one of my pet peeves is hard-to-read source HTML)!

Each photo is stored in the array $photodisp for use in our next step: formatting for output.

Format Your Photos for Output
Now that we have all of the photos stored in an array, we set up a new function to create a web-ready block of HTML for displaying all of your photos.

  function display($numrows=6,$head="Photos on Flickr") {
    $photodisp = $this->parse();
    $i = 0;
    $thumbs = <<<____________EOD

      <!--// FlickrFeedr by Ennui Design
             www.EnnuiDesign.com | answers@ennuidesign.com //-->
        <div class="ennui_widget_head">
          {$head}
        </div>
        <div class="ennui_widget">
____________EOD;
    while ( $i < $numrows ) {
      $thumbs .= $photodisp[$i];
      $i++;
    }
    $trim = str_replace('http://api.flickr.com/services/feeds/photos_public.gne?id=', '',$this->feed);
    $user = str_replace('&lang=en-us&format=rss_200','',$trim);
    $thumbs .= <<<____________EOD

          <div class="ennui_widget_footer">
            <span>
              <a href="http://www.flickr.com/photos/{$user}/"
                title="http://www.flickr.com/photos/{$user}/">
                View All Photos on Flickr
              </a>
            </span>
          </div>
        </div>
      <!--// End FlickrFeedr by Ennui Design //-->
____________EOD;
    return $thumbs;
  }

Let's break that down. First, we'll be passing the variable $numrows when we call this function. This is how many photos we're going to display on the site. The default value is 6, which works well in 1, 2, and 3 column displays, making it a safe bet.

Then in line 02, we run the parse function we just created. This loads the array into the variable we'll call $photodisp for ease of use. Line 03 sets the variable $i to zero. We'll use this for a while loop to build our content.

Lines 04-10 start our output (using the heredoc syntax again). We're building the header of our display, as well as starting the div that will contain the photos.

The meat of this function happens in lines 11-14. Here, we are essentially telling the function, "while the number of photos we've grabbed is less than the number we're allowed to display, grab the next photo from the array." And, since we already formatted the output in the parse function, we don't have to do anything else with it!

In lines 17 and 18, we take the feed URL and trim out just the user name (in my Flickr feed, this user name is "22352410@N07"). This way, we can use it to send a site visitor to your Flickr photostream's homepage, eliminating any further data input or reliance on a visitor's memory of an additional URL.

Lines 19-27 finish up the HTML for the display, and then line 29 returns our output.

That's it! Now all we have to do is call the class and let 'er rip!

Implementing the Class
Our last step is to place the code on our homepage that will call this class and produce our new Flickr display!

<?php
  include('_class/flickr.php');
  $flickr = new flickr('http://api.flickr.com/services/feeds/photos_public.gne?id=22352410@N07&lang=en-us&format=rss_200');
  echo $flickr->display(8,"Ennui on Flickr");
?>

Wrap-Up
We have now successfully created a PHP class that loads, parses, and displays a Flickr user's photostream feed! With a little CSS styling and proper placement, you can now seamlessly integrate your Flickr stream into your own website.

Below, you can download the complete files used to create the fully functional Flickr RSS parsing demo.

Download the files for this tutorial (ZIP Archive, 2KB)

Enjoy! Please leave any questions and suggestions in the comments, as well as links to your site with the Flickr RSS parser in place!

Posted Sep 21, 2008 by Jason Lengstorf.
This entry is filed under flickr, rss, simplexml, tutorial, and php.

Want more content like this? Subscribe for FREE!

Comments for This Entry

GravatarPhilip08:24PM on December 01, 2008

How come it's not working? Even your example on the "fully functional Flickr RSS parsing demo" page isn't. It'll be a really big help if you get this working. Thanks!

GravatarJason Lengstorf10:54AM on December 02, 2008

@Philip:
Turns out my old Flickr page went down, so the RSS feed I was using wasn't valid any longer.

The demo has been updated with my new Flickr RSS feed, and it's working again.

Thanks for bringing this to my attention!

-Jason

GravatarPhilip06:50PM on December 02, 2008

hey jason thanks for updating this man, i'll definitely use this on my site!

Big thanks! really appreciate this, I'll be working on this when i get off from work

GravatarDavid02:12PM on March 06, 2009

Hey what should i edit for only text rss?
I like to parse text rss and found your tutorial.
Can I $thumb['width']; and height delete? Or change to something else? Pls help me

GravatarJason Lengstorf02:30PM on March 06, 2009

@David

To parse text, you would follow the same process as above, but the post-processing would be different. For instance, if you wanted to pull the contents of the node, you could do the following:

foreach($rss->channel->item as $item) {
$description = $item->description;
$display .= '

' . $description . '

';
}

Let me know if that helps! Also, there's another article I've written on this site that goes into a little bit more detail about reading RSS with SimpleXML: http://ennuidesign.com/blog/FlickrScrollr+Explained%3A+PHP/

Good luck!

GravatarAnthony12:52AM on March 15, 2009

Thanks for this great tutorial! I will be trying this out tomorrow! Thanks for taking the time to do this.
Would love to see a tutorial on how to display blog rss feeds on another web page or displaying last songs played at last.fm!

Gravatarbas07:40AM on March 30, 2009

great, just what i needed, thanks!

GravatarCarl Cahill06:59AM on April 16, 2009

Hi Jason, I really like this tutorial. Its going to be really useful for my website, although i'm having problems with the code. Im quite new to php and still learning, which is the problem. I've done the tutorial, but was hoping to download the files but your link has not worked. I was hoping to compare it to my code. any chance you could either reinstate the link or send it to me personally?

Thanks Jason

Carl Cahill

GravatarJason Lengstorf09:52AM on April 16, 2009

@Carl Cahill:

Sorry abut that. My .htaccess file was out of date. :)

It should be fixed now. Let me know if you have anymore trouble!

GravatarChristopher Reichert11:15AM on May 06, 2009

Hi Jason,

Nice. I wonder if there is a way to source a feed from Flickr, but then have each image clickable to a unique URL? I am trying to create a site that shows baby clothing pics from a Flickr collection(s), but when you click on a given pic, it redirects to a landing page with more details on the clothing piece.

I was thinking of the Google slideshow (http://www.google.com/uds/solutions/slideshow/) but var_feed that sources from Flickr (or a mysql db) and then allows for the click through redirect.

Any thoughts on this?

Thanks!

GravatarJason Lengstorf11:27AM on May 06, 2009

@Christopher Reichert:

The only thing I can think of that would be simple to implement would be to create pages that correspond to the image titles and use that as the URL.

Example:

Photo title -- Product 01

Page URL -- http://example.com/products/Product+01.html

You could use

$link = urlencode($item->title);

instead of the current code, and that would do it.

Let me know if that works for you!

GravatarJ K05:48AM on May 20, 2009

i execute the feed script i got error as "Node no longer exists".

GravatarJason Lengstorf12:47PM on May 21, 2009

@J K:
Does it give you a line number or any further information? I haven't run into that error before...

GravatarRolle08:18AM on May 25, 2009

Thank you, this is very useful! I coded medium thumb and big photo (original size) -urls because I needed them. Good work!

GravatarGwilym03:19PM on June 14, 2009

Hi - great tutorial. I have a feed I am trying to get 27 posts out of but for some reason I only get the first 20 - any idea how to change that?

:-)

GravatarJason Lengstorf07:44PM on June 14, 2009

@Gwilym:
Some RSS feeds only generate a limited number of entries. To work around it, you could look into a way to save entries from the feed into a flat file or database.

You might be able to use something like Yahoo! Pipes or Google Reader to do that, but I'm not sure.

Let me know what you work out!

Gravataramp06:39AM on June 21, 2009

one more function

http://www.phpinform.com/2009/06/21/php-rss-to-array-function/

Post a Comment

Want to show your face? Get a gravatar!

ALLOWED TAGS: <tt><strong><em>