Create a Neat Flickr Gallery with SimplePie

Create a Slick Flickr Gallery with SimplePie

Feb 25th in PHP by Japh

I've wanted to write a tutorial for quite some time now, and APIs have always been a particular interest of mine. So with my wife's recent foray into photography, I decided a Flickr tutorial would be first cab off the rank! Using RSS, Flickr and jQuery all together was pretty fun too.

PG

Author: Japh

Japheth Thomson is currently the Technical Director for a design, development and training studio in Australia, running a small team of developers. Japheth has been developing websites for approximately 10 years, and specialises in PHP, MySQL, HTML, CSS and Javascript. He also enjoys working with WordPress and APIs, and does the occassional bit of training.

final product

Ok, so we're going to be touching on a number of technologies for this tutorial. We'll be using an RSS feed from Flickr, a bit of PHP, and some jQuery to make things nice and interactive! We'll use SimplePie to handle the RSS feed, as it makes life much easier, and can be used in any other projects where RSS feeds are involved.

Step 1

Create a file called "index.php", and start it out with a fairly basic HTML structure to house the various components of our Flickr feed.

<body>
    <div class="page-wrapper">
        <div class="header">
            <h1></h1>
        </div>
        <div class="album-wrapper">
        </div>
        <div class="footer">
        </div>
    </div>
</body>

Pretty standard stuff, note that we've added classes for the header and footer, but more importantly, the album-wrapper. This is the div where we will output all the images that come in from our Flickr feed.

Step 2

Make two new folders called "includes" and "cache", then download SimplePie and copy it in to the "includes" folder. SimplePie cleverly stores a cached version of your Flickr feed locally to help speed up future visits. Note: If you're not doing this on Windows, don't forget to make sure the "cache" folder is writeable.

<?php
require_once('includes/simplepie.inc');
$feed = new SimplePie('http://api.flickr.com/services/feeds/photos_public.gne?
id=28211532@N07&lang=en-us&format=rss_200');
$feed->handle_content_type();
?>

Inserting this code into the very top of your "index.php" file gives us access to the SimplePie library to handle the RSS feed for us. Also, the second and third lines create a new feed object based on the RSS URL for your Flickr feed.

Step 3

Now we can start littering our HTML with snippets of PHP to output information from our Flickr feed. Some of the key function SimplePie provides are:

$feed->get_title(); // Returns the title of the RSS feed
$feed->get_image_url(); // Returns the image for the feed, in the case of Flickr, the user's 
avatar
$feed->get_items(); // Returns an array of the items in the feed, in the case of Flickr, the 
photos with their descriptions etc.

Each item returned by get_items() also has it's own get_title() etc. to retrieve it's various elements. For a full list of the functions available to SimplePie, check out the SimplePie documentation.

So the first functions we'll call in our script will be the title and heading:

<title>Flickr Album: <?php echo $feed->get_title(); ?></title>
<h1><img class="feedIcon" src="<?php echo $feed->get_image_url(); ?>" border="0"
alt="<?php echo $feed->get_title(); ?>" /> <?php echo $feed->get_title();
?></h1>

Step 4

Before we can begin looping through the photos in the feed, we need to write two short functions. The first one locates the image tag within the description of a photo in the RSS feed. You can write this function between the existing PHP tags at the top of the script.

function image_from_description($data) {
    preg_match_all('/<img src="([^"]*)"([^>]*)>/i', $data, $matches);
    return $matches[1][0];
}

The second function allows you to select the size of the image to retrieve from Flickr, but adjusting the filename in a image tag. This function should also be placed between the existing PHP tags at the top of the script.

function select_image($img, $size) {
    $img = explode('/', $img);
    $filename = array_pop($img);
    
    // The sizes listed here are the ones Flickr provides by default.  Pass the array index in the 
$size variable to selct one.
    // 0 for square, 1 for thumb, 2 for small, etc.
    $s = array(
        '_s.', // square
        '_t.', // thumb
        '_m.', // small
        '.',   // medium
        '_b.'  // large
    );
    
    $img[] = preg_replace('/(_(s|t|m|b))?\./i', $s[$size], $filename);
    return implode('/', $img);
}

Step 5

Now we can loop through the photos in the RSS feed, and output them. We will use a for loop to go over each item in the feed.

<div class="album-wrapper">
    <?php foreach ($feed->get_items() as $item): ?>
        <div class="photo">
            <?php
                if ($enclosure = $item->get_enclosure()) {
                    echo '<h2>' . $enclosure->get_title() . '</h2>'."\n";
                    $img = image_from_description($item->get_description());
                    $thumb_url = select_image($img, 0);
                    echo '<img id="photo_' . $i . '" src="' . $thumb_url . '" />'."\n";
                }
            ?>
            <p><small><?php echo $item->get_date('j F Y | g:i a'); ?
></small></p>
        </div>
    <?php endforeach; ?>
</div>

To explain this bit of code, as we loop through we output a new div that we can style later. Inside each div, we use the functions we wrote previously to get a particular image size (I chose square for ease of styling). We're also outputting the title of each photo before outputting the photo itself, and the date beneath each photo.

Step 6

Now it's time to give the album some style! So firstly to give some basic structure to the base HTML structure, I'll set some fonts, widths, margins etc. Also a little style to sort the alignment of the Flickr feed's icon image. Don't forget to link your stylesheet file in the head section of your HTML first of all.

<link rel="stylesheet" type="text/css" href="style.css" />

Then insert these CSS rules into your "style.css" file:

body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    background-color: #222;
    width: 960px;
    margin: 0;
    font-size: 0.75em;
}

.page-wrapper {
    background-color: #444;
    text-align: left;
    width: 960px;
    margin: 0 auto;
    padding: 20px;
    position: relative;
    top: 30px;
    left: 30px;
    overflow: auto;
}

.page-wrapper h1 {
    font-size: 1.8em;
}

.page-wrapper h2 {
    font-size: 1.2em;
    color: #222;
}

.page-wrapper .feedIcon {
    vertical-align: middle;
    padding: 0 10px;
}

Then some style to be applied to each of the photo divs:

.album-wrapper .photo {
    width: 200px;
    background-color: #666;
    text-align: center;
    vertical-align: middle;
    float: left;
    padding: 10px;
    margin: 10px;
}

.album-wrapper .photo img {
    border: none;
}

.album-wrapper .photo small {
    color: #aaa;
    font-size: 0.9em;
}

Step 7

Now to add a bit of interactivity, we'll bring in some jQuery. I think it'd be nice to have a hover effect, and the ability to click an image and see a larger version. Include the jQuery script file, which you can get the latest version of from jquery.com, also make yourself a "script.js" and include that in the same way.

<script type="text/javascript" src="jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="script.js"></script>

Step 8

The first bit of jQuery to add into your "script.js" file, is a $(document).ready() to handle everything you want jQuery to do, after the document has loaded.

$(document).ready(function() {
    $('.photo').fadeTo(0, 0.5);
}

This will fade each div with the class ".photo" to 50% as soon as the document is fully loaded and ready. Next we'll make the images light up when the mouse hovers over them.

$(document).ready(function() {
    $('.photo').fadeTo(0, 0.5);
    
    $('.photo').hover(function(e) {
        $(this).stop().fadeTo('slow', 1.0);
    }, function(e) {
        $(this).stop().fadeTo('slow', 0.5);
    });
});

These extra 5 lines tell jQuery to make each photo, on hover, fade to 100%, and when the mouse goes off again, fade back to 50%. (Thanks to Mike Schneider and Simon in the comments for some changes here)

Step 9

It'd be nice to make the thumbnails clickable, so you can view a larger version of the images. To do this, we'll use Thickbox, built on jQuery.

<link rel="stylesheet" type="text/css" href="thickbox.css" />
<script type="text/javascript" src="thickbox-compressed.js"></script>

Download Thickbox, and then include it in the head of your "index.php" file, as shown above.

Once they're included, edit the following lines to work out the URL to a full image, and add in a link with a class of 'thickbox'. This activates Thickbox, and it should just work, I've also added title which provides a caption.

$full_url = photo($url, 'full');
echo '<a href="' . $full_url . '" class="thickbox" title="' . $enclosure->get_title() . 
'"><img src="' . $thumb_url . '" alt="' . $enclosure->get_title() . '" />
</a>'."\n";

Complete!

That's it! You should now have a script that displays a Flickr feed for you, and allows you to click them and see a larger version. Enjoy!

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


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Jash Sayani February 25th

    Great Tutorial !!

    BTW, pls post some Python tuts…

    ( Reply )
  2. PG

    insic February 25th

    I havent used simple pie before. This time I should try. The Demo looks nice

    ( Reply )
  3. PG

    pad February 25th

    The lightbox plugin doens’t work for me (firefox 3) :(

    ( Reply )
  4. PG

    Hildds February 25th

    Nice, nice, man :D

    ( Reply )
  5. PG

    Don February 25th

    Line 9 in Step 8 should read });

    ( Reply )
  6. PG

    Craig Farrall February 25th

    Nice tutorial Japh mate, I will have a look at putting this on a website in the future, keep up the good work ;)

    ( Reply )
  7. PG

    Robbie Done February 25th

    Nice Flicr gallery, thanks ;)

    ( Reply )
  8. PG

    C Mejia February 25th

    Insic is so Maganda! Oh the tutorial is fantastic also

    ( Reply )
  9. PG

    Ryan O. Hicks February 25th

    awesome

    ( Reply )
  10. PG

    M.A.Yoosuf February 25th

    nice, but im reading it again

    ( Reply )
  11. PG

    David Singer February 25th

    Looks nice but 42 errors on one page… Needs some validation work.

    http://validator.w3.org

    ( Reply )
  12. PG

    Andrea February 25th

    Nice work! i like it very much. But how difficul is to make this for joomla plug-in?

    ( Reply )
  13. PG

    Craigsnedeker February 25th

    Sweet tut!

    ( Reply )
  14. PG

    Roland Porth February 25th

    yikes – i’ll second the 42 errors

    Wow! using class .photo_ instead of multiple ids #photo_ would help: ids are only supposed to appear once on a page – classes are for multiple instances.

    Putting alt tags on the images would also take care of a lot of those validation errors.

    You also forgot to close the html tag at the bottom of the document

    ( Reply )
  15. PG

    Jeff February 25th

    very nice tut, checkout http://www.liteflick.com for a site that has a demo of flickr photos displayed in a jquery lightbox. you can also search for photos.

    ( Reply )
  16. PG

    Mike Schneider February 25th

    Under step 8, you should correct the code to this:

    $(document).ready(function() {
    $(’.photo’).fadeTo(’fast’, 0.5);

    $(’.photo’).hover(function(e) {
    $(this)..stop().fadeTo(’slow’, 1.0);
    }, function(e) {
    $(this).stop().fadeTo(’slow’, 0.5);
    });
    }

    The stop() will prevent the animation from continuously looping if u mouse over really fast repeatedly.

    ( Reply )
  17. PG

    nixie February 25th

    Thank you! I liked it

    ( Reply )
  18. PG

    Bryan P. February 25th

    Thanks for help. I will have to try that out in my next project that uses Flickr photos.

    ( Reply )
  19. PG

    FireDart February 25th

    Cool

    ( Reply )
  20. PG

    JohnONolan February 25th

    AWSOME! Definitely going to use this and get rid of that nasty javascript feed of mine!

    ( Reply )
  21. PG

    Japh February 25th

    Thanks for the comments so far everyone! I’ll see about submitting a slight revision to rectify the issues that snuck in there.

    Learned a few things already for future tuts too! ;)

    ( Reply )
  22. PG

    Satkrit February 25th

    When I downloaded the demo it was all messed up! Please look into it.

    Otherwise pretty good tutorial.

    ( Reply )
  23. PG

    Japh February 25th

    @Satkrit I’d be happy to, but I might need you to give a little more info. What was “all messed up” exactly?

    ( Reply )
  24. PG

    Braden Keith February 25th

    The link to simplepie.org is linked to simpliepie.org. Just so you know.

    ( Reply )
  25. PG

    mepho February 25th

    Nice tutorial!

    another addition you could add the next and previous buttons for the lightbox

    ( Reply )
  26. PG

    Japh February 25th

    Thanks! I have submitted an update to address some of the earlier mentioned concerns. So hopefully the guys will update the article sometime soon :)

    ( Reply )
  27. PG

    Simon February 26th

    Damn, really nice one Japh ! I love it !
    I’m juste wondering about this one:
    1. $(document).ready(function() {
    2. $(’.photo’).fadeTo(’fast’, 0.5);
    3. }
    If you want to fade immediatly after loading, wouldn’t it be nicer to juste write it like this:
    1. $(document).ready(function() {
    2. $(’.photo’).fadeTo(0, 0.5);
    3. }
    ? This makes it fade immediatly.
    However, thanks again ! :)

    ( Reply )
  28. PG

    Zarathustra February 26th

    Last time I looked at SimplePie it weighed about 500k! Is that still the case, because in the end I opted for a much lighter solution to get a Flickr feed parsed into my footer. “lastrss.php” . I got it from here: http://lastrss.webdot.cz/ it’s about 200 lines and does what I needed it to do. (Which granted wasn’t a lighbox driven gallery etc)

    Back to my point…is SimplePie still a fatty pie?

    ( Reply )
  29. PG

    Bjorn February 26th

    Was looking for a new flickr gallery solution, although I’m not sure this is the way I’ll go… Thanks for the info, either way!

    ( Reply )
  30. PG

    Ryan February 26th

    Obviously the “42 errors” is a simple mistake. Give the guy a break and troll somewhere else.

    ( Reply )
  31. PG

    AnotherFlava February 26th

    Cool tutorial but why use Simplepie or any other library for that matter, when php has built in functions to deal with xml(rss) SIMPLEXML here is a quick sample I knocked out http://anotherflava.com/?p=309

    The extra overhead is really unnecessary!!!

    ( Reply )
  32. PG

    Qiming February 26th

    Absolutely Brilliant

    ( Reply )
  33. PG

    dedi February 26th

    good tutorial

    ( Reply )
  34. PG

    Zarathustra February 27th

    @AnotherFlava that look to be extremely elegant. Maybe you could expand that into a full tutorial over on your blog?

    ( Reply )
  35. PG

    Martyn February 27th

    this is defiantly something i would be happy to use in the future. Never used simple pie before, so would be good to get to grips with it..

    ( Reply )
  36. PG

    Ihab Essam February 28th

    Oh,yeah mr.japh that’s the more intersting Tutorial..

    ( Reply )
  37. PG

    Japh March 2nd

    The article has been updated now. Thanks everyone for your great comments! :)

    ( Reply )
  38. nice works thanks for the tutorial..

    ( Reply )
  39. PG

    Shibi Kannan March 5th

    Hi,
    nice tutorial, unfortunately it didn’t work for me. Did any of you guys actually try this one. First of all both jquery and simplepie have released newer versions since this article. Second I tried both versions with the demo files provided on Linux server supporting php and all I can get is the css box layout. The simplepie is not pulling my flcikr feed. I tried both rss and atom feed urls but still wont work. I have tested all major browsers. I used firebug to look at the output, html and css part looks ok but the h1 tags where the feed info should show up dynamically is empty. Can someone please help. I have also provided the link to my page where I have uploaded the contents of the edited demo files.
    Thank you,
    Shibi Kannan

    ( Reply )
  40. PG

    Shibi Kannan March 5th

    Dear All,
    Please ignore my previous comment. I uploaded the demo files in another server and it works just fine. Some kinda server side issue prevented it from happening before. But a new problem came up. The thumbnail view is OK but the full view says image not available. I have set full permissions to the cache directory. But still it wont show. I also made sure that the Flickr photostream is publicly available. Any suggestions to find the problem…
    link: http://vetcormesh.info/portfolio/
    Thank you,

    Shibi Kannan

    ( Reply )
  41. PG

    Artem March 5th

    Hey!

    in Step 9 on line 1 little mistake – instead call function photo() you need call select_image():

    $full_url = photo($url, ‘full’); –> $full_url = select_image($img, 4);

    ( Reply )
  42. PG

    mike March 9th

    i’m getting this error:

    Warning: ./cache/959135df4b101617458e89a28af1c788.spc is not writeable

    and the jQuery scripts arn’t working….i am dynamically generating the html for the gallery…is there a path issue at work i can’t figure out?

    ( Reply )
  43. PG

    James Regal March 10th

    Is this all done in Dreamweaver?

    ( Reply )
  44. PG

    adrimar March 18th

    Hi everybody!

    I really like the tutorial thank you Japh.

    I’ve been working with the tutorial, but I have some warning error.

    1. Warning: ./cache/60f66917d881bd2a639153c613f399b1.spc is not writeable in C:\wamp\www\includes\simplepie.inc.php on line 1773
    How I make it writeable?

    2. Notice: Undefined variable: i in C:\wamp\www\index.php on line 53

    3. I can’t see the pictures, show me only a blue question mark .

    ( Reply )
    1. PG

      Septian Maulana Yusuf (From Indonesia) April 12th

      You and me is not different, I have error same with your problem

      ( Reply )
    2. PG

      Brian April 19th

      for the undefined variable i add in mg and it should be okay as seen below
      It should be img

      ‘.”\n”;
      regards
      Brian

      ( Reply )
  45. PG

    kakday April 8th

    cool

    ( Reply )
  46. PG

    Arturo José Monterroso García April 11th

    In the regular expression to chose a given size for each image there’s a mistake, you have this: ‘/(_(s|t|m|b))?\./i’, and it won’t work with ‘_b’ because it also replaces some other characters in the url, making it invalid.

    I changed it to ‘/(_(s|t|m|b))+\./i’ and it works with all urls and sizes so far, thanks for this great tutorial.

    ( Reply )
  47. PG

    Septian Maulana Yusuf (From Indonesia) April 12th

    Hard Tutorial!!!!, I’cant Follow it. . .

    I try at home, the page of Album can’t display. . .

    ( Reply )
  48. PG

    Brian April 19th

    This is a very good tutorial, Im just stuck at the last hurdle.
    when i click on an image the image doesnt appear, the box opens and the name of the image appears but the photo doesnt appear. I presume im supposed to modify something in the thickbox files but my brain has gone dead at the moment. any help would be appreciated. Thanks

    ( Reply )
  49. PG

    Brian April 19th

    I just read somewhere else that I might need a pro flickr account. Does anybody know if this is true?

    ( Reply )
  50. PG

    Andrew April 27th

    cannot wait to try this out, seems great. many many thanks

    ( Reply )
  51. PG

    LuK August 3rd

    Thank you very much for the tutorial, just implemented it in an actual project where I mix together three news-feeds (state, national, international), I could get it done that the scroller shows the favicon of the original Website but this adds no functionality to it because it’s the same site that provides all three feeds, so the favicon is always the same and the user can’t see from which feed the post comes (wouldn’t it be practical to see if the news post is state-related, country-related or international-related?)…

    so I’m looking for a possibility to add either a custom favicon or a custom image, depending from which feed the post comes…

    for the image I use the feed-image like this:
    <img src=”get_image_url(); ?>” alt=”Feed Image” />

    now, instead of taking the feed image (which is also everytime the same and not the right size, so it gets blurred [is that the right word for an image that is out of proportions?=D]), I would like to add a custom image depending on the feed, but I don’t have that in dept knowledge of php =/, so maybe somebody in here knows how to do it…

    I would place the 3 custom images in some folder on the server.

    ( Reply )
  52. PG

    Mullikin October 12th

    Excellent post looks like a neat way to get and display photos.

    Hose Reels

    ( Reply )
  53. PG

    Dan October 16th

    This is a great script, thanks for your time in creating it.
    I have implemented it and it works fine, however for a couple of photos i get the error message ”
    this photo is currently unavailable ” when the thumbnail is clicked on and no larger pic is shown, yet the thumbnail displays fine.

    I have a found a possible solution – does anyone know how to implement this into the script?

    Someone on the Flickr forum presented the answer:
    “I’m not 100% sure but I think it’s a combination of some slightly
    dodgy scripting and the fact that you’ve uploaded your photos is a low
    resolution. Flickr makes several sizes (square, thumbnail, small,
    medium and large) of your photos available with predictable URLs, and
    also makes the original size available with a different URL.

    The gallery script you’re using seems to be generating what would be
    the predictable URL for you ‘large’ size, rather than actually
    querying Flickr for the available sizes. That doesn’t work on your
    account since your ‘large’ size is actually your ‘original’, so
    nothing exists at the predictable URL for large – you’ve only actually
    got square, thumbnail, small, medium and original.

    You can probably fix it by either modifying the script so that it
    checks with Flickr for the URL of the largest available size for each
    individual photo, or by uploading your photos in a higher resolution
    so that Flickr does generate a ‘large’ size.”

    ( Reply )
    1. PG

      Milo November 3rd

      The reason for this is that Flickr doesn’t actually create a Large size if the image is too small (in my case under 1300px wide).

      The only workaround I found so far, was to switch

      ‘.’, // medium
      ‘_b.’, // large

      to

      ‘_b.’, // medium
      ‘.’, // large

      …however, that limits you to displating only medium sized versions. Instead, I just uploaded big enough pictures to Flickr and it works fine.

      I would like a proper solution though.

      ( Reply )
  54. PG

    Jacob Louis October 17th

    This is awesome! I am so happy to find an alternative to flash for creating a flickr gallery my clients can update themselves. Thank you!

    I have a question though…

    When they uploaded a new photo it didn’t show up right away. Is there any way to make it update simple pie automatically without deleting the cache file?

    ( Reply )
    1. PG

      Jacob Louis October 17th

      Never mind I got it…

      I just set it in the simplepie.inc

      var $cache = false;

      ( Reply )
  55. PG

    Jacob Louis October 17th

    Does anybody know how I would add fancy zoom to this gallery?

    ( Reply )
  56. PG

    John October 21st

    Is it difficult to implement this into Wordpress? I tried three times already and failed. :(

    I’m assuming I’d have to use Wordpress’ built-in jQuery library…

    Anyone care to shine some light?

    ( Reply )
  57. PG

    Dan November 4th

    Great Scirpt, I have used it on a few client sites. How would I go about implementing pagination via php or JQuery?

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 4th