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.

Leave a Reply

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