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:



$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:\/\/\/\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>';


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:

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

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


function jsonFlickrFeed(feed)
  var imgPattern = /(http:\/\/\/\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>';


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

Leave a Reply

Note: Only a member of this blog may post a comment.