jQuery: Flickr cross-fade image rotator

In this post I'm going to show you a simple implementation (yet to be a little bit enhanced) of a Flickr cross-fade image rotator with jQuery. The script itself is made up of two components: a call to the $.getJSON() method to fetch the JSONP Flickr feed and a JavaScript timer to rotate the retrieved images. First of all, let's define our CSS styles to display our rotator:

jQuery: a Flickr gallery with JSONP

In this post I'm going to show you how to create a simple Flickr gallery with jQuery and JSONP. JSONP stands for JSON with Padding and allows you to execute cross-domain AJAX requests using JavaScript (in this case, jQuery). We're going to use the public JSON feed of Flickr to display a simple gallery made up of nine pictures. First of all, let's take a look at the inner structure of a JSON Flickr feed:

PHP: fetching only images from a Flickr feed

A Flickr feed is very useful when we want to retrieve our images uploaded on a Flickr's album. Within this feed, we're only interested in the description element contained inside each item element. By default, all the content of this element is served as HTML and it's a little bit redundant because it also contains unnecessary information, such as "Gabriele Romanato posted a photo" repeated several times. Let's say that we want only the images, with no links or descriptions. How can we achieve this result?

PHP allows us to use Perl-Compatible Regular Expressions (PCRE) to select some portions inside strings or, more generally, textual content. So we're going to use them together with the SimpleXML library. Example:

$flickr_rss = simplexml_load_file('your/feed/url');
       

        $entries = $flickr_rss->channel->item;
        $i = -1;
        $html = '';
        $html .= '<div class="pics">' . "\n";
        
        do {
        
          $i++;
          
          $entry = $entries[$i];
          $content = $entry->description;
          $pre_content = preg_replace('/\n+|\r\n+/', '', $content);
          $img_src_re = preg_match_all('/src=".+"/', $pre_content, $matches);
          $src = str_replace('src="', '', $matches[0][0]);
          
          $html .= '<img src="' . $src . '" />' . "\n";
                           
        
        } while($i < 4);
        
        $html .= '</div>' . "\n";
        
        
        echo $html;

We're actually retrieving only the first five images of our album using a do...while loop. Since we know that the URL of each image is contained within a src attribute, we use a regular expression to accomplish this task. Then we remove the src=" characters from the string using str_replace(). Note that since we've used preg_match_all(), the returned result is an array whose first value is in turn another array, so our value is contained in the first item of this second array.

Demo

Live demo

A Flickr gallery with CSS

In this post I'm going to show you how to stylize a simple Flickr gallery with CSS. We'll use floats and image resizing to get the desired effect. Additionally, we'll use some background images in order to add some extra nice touches to our gallery. First of all, we need a markup to start with. Here's a sample:

<div id="gallery">
 
 <ul>
  
  <li><a href="#"><img src="flickr-gallery/gallery/1.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/2.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/3.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/4.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/5.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/6.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/7.jpg" alt="" /></a></li>
  <li><a href="#"><img src="flickr-gallery/gallery/8.jpg" alt="" /></a></li>
  
 </ul>
 
</div>

We have a container and an unordered list which, in turn, contains images and their parent links. In this example we don't use the alt attribute on each image, but you're strongly encouraged to do so for accessibility reasons. Now let's move to CSS:

#gallery {
 
 margin: 0 auto;
 width: 640px;
 padding: 0 0 0 55px;
 background: url(flickr-gallery/flickr.png) no-repeat 0 0;
 
}

#gallery ul {
 
 width: 500px;
 margin: 0;
 height: 100%;
 overflow: hidden;
 padding: 0;
 list-style: none;
 
}


#gallery ul li {
 
 width: 120px;
 height: 100px;
 float: left;
 padding-top: 55px;
 background: url(flickr-gallery/item.png) no-repeat 50% 0;
 
}

#gallery ul li a {
 
 display: block;
 width: 100%;
 height: 100%;
 
 
}

#gallery ul li a img {
 
 border: none;
 width: 100%;
 height: 100%;
 display: block;
 
} 

The main container has a background image showing the Flickr logo, so we've added some left padding to insert it properly. The unordered list will contain floated elements, so we clear and contain them using the overflow property. As you can see, all list items are floated and have a background image (a marker) on their top. This image is horizontally centered. Finally, links and images have their dimensions expressed in percentages so that they scale along their containers. You can see this demo here.

Flickr mashups with PHP and JavaScript

Flickr, PHP, JavaScript: three faces of the same coin. Since I believe that the Web 2.0 phenomenon has still to show out all its potential, it's sometimes useful to study some code written by others. A good example of this is surely Flickr Mashups by David Wilkinson. This book is an exciting and stimulating resource on all the possible combinations of Flickr API, PHP and JavaScript. For example, here's a combination of PHP, JSON and JavaScript for creating badges:

PHP

include("http://api.flickr.com/services/feeds/groups_pool.gne?id=myID&format=php");

$s = "";

$s .= '<div class="badge">';
$s .= '<p class="badge-title"><a href="' . $feed['url'] . '">' . $feed['title'] . '</a></p>';
$s .= '<ul class="badge-items">';

$items = $feed['items'];

for ($i = 0; $i < count($items); $i++)
{
  if (preg_match('/(http:\/\/static.flickr.com\/\d+\/\d+_[0-9a-z]+)_m\.jpg/',
    $items[$i]['description'], $result))
  {
    $image = $result[1] . '_s.jpg'; 
    $s .= '<li class="badge-item"><a href="' . $items[$i]['url'] . '"><img src="' . $image . '" /></a></li>';
  }
}

$s .= '</ul></div>';

echo($s);

This script includes an HTML snippet made up by all the required images, plus their title and description. The PCRE used in the above code serves as an handy way to select only the desired images. The JavaScript way, instead, requires the JSON format. You need to include the following script element in your page:

<head>
<script src="http://api.flickr.com/services/feeds/groups_pool.gne?id=81474450@N00&format=json" type="text/javascript"></script>
</head>

Then you can add your custom script for retrieving and parsing images:

JavaScript

function jsonFlickrFeed(feed)
{
  var imgPattern = /(http:\/\/static.flickr.com\/\d+\/\d+_[0-9a-z]+)_m\.jpg/;
  var s = "";

  s += '<div class="badge">';
  s += '<p class="badge-title"><a href="' + feed['link'] + '">' + feed['title'] 
      + '</a></p>';
  s += '<ul class="badge-items">';

  var items = feed['items'];
  for (var i = 0; i < items.length; i++)
  {
    var result = imgPattern.exec(items[i]['description']);

    if (result != null)
    {
      var image = result[1] + '_s.jpg';            
      s += '<li class="badge-item"><a href="' + items[i]['link'] + '"><img src="' 
          + image + '" /></a></li>';
    }
  }

  s += '</ul></div>';

  document.writeln(s);
}

Of course you can avoid the writeln() method by inserting a placeholder in your page and using the innerHTML property instead.

Parsing a Flickr feed with SimpleXML

Parsing a Flickr RSS feed requires some preparatory steps. First of all, I tried to download a static copy of my feeds using wget just to study the file structure. Wrong choice! In fact, the format returned was Atom, not RSS. So I used the following approach:

$file = file_get_contents('http://api.flickr.com/services/feeds/photos_public.gne?id=31968388@N02&lang=it-it&format=rss_200');
echo $file;

So I got the correct format. Parsing the feed is quite a simple task:

$rss = simplexml_load_file('http://api.flickr.com/services/feeds/photos_public.gne?id=31968388@N02&lang=it-it&format=rss_200');
    
    foreach($rss->channel->item as $entry) {
    
    
    
        $title = $entry->title;
        $raw_published = $entry->pubDate;
        $published = str_replace('-0700', '', $raw_published);
        $raw_content = $entry->description;
        $content = html_entity_decode($raw_content, UTF-8);
        
        
        echo '<li>' . "\n" . '<h2>' . $title . '</h2>' . "\n" . '<p class="pubdate">' . $published . "</p>\n" . 
        $content . "</li>\n";
    
    
    
    
    }

Two notes here:

  1. you need to start parsing from the root element, not from the SimpleXMLObject itself
  2. the description element contains markup that needs to be expanded using the html_entity_decode() function

You can see this test here.

Parsing a JSON Flickr feed with jQuery

Parsing a JSON Flickr feed with jQuery is not so simple as it could seem, because this requires a firm knowledge of two factors: the feed URL and the correct syntax to use with the jQuery's getJSON() method. First the URL, that must be in this form:

http://api.flickr.com/services/feeds/photos_public.gne?id=31968388@N02&lang=it-it&format=json&jsoncallback=?

where id is your Flickr ID and lang is your preferred language. However, the key parameter is jsoncallback. Without this, your script will fail and it'll return null. Second, the syntax of the jQuery's method:

$.getJSON(url, function(data){});

where data is a reference to your JSON object. Now, let's test something:

$(document).ready(function() {

    $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=31968388@N02&lang=it-it&format=json&jsoncallback=?', 
    function(data) {
          
      var ul = $('<ul></ul>');
      var html = '';
      
      $.each(data.items, function(i,item) {            
            
             html += '<li><h3>' + item.title + '</h3><p><a href="'+item.link+ '"><img src="'+item.media.m+ '"/></a></p></li>';

            
      });
      
      ul.html(html);
      
      
      $(ul).appendTo('body');
        
    
    });


});

You can see the result here. As you can see, preliminary requirements are more difficult to understand than the actual implementation.

Flickr API: getting started

I activated my Flickr API key this very morning and downloaded the documentation. I have to say that this kind of thing is really interesting, because it allows you to create rich mashups with a little effort. I'm not a stickler of the JSON/JavaScript approach, because I think that this kind of format should be handled using a server-side language instead of relying on a client-side support that, as many of you know, is not always available (PHP supports JSON very well, though).

As you can see, this blog integrates Flickr photos, but I don't have access to the full details of the implementation, so the best thing I can do is to write my own code and see it by myself.