Custom flickr sidebar via wget, cron & PHP
Wednesday, July 29th, 2009The new site launched with a sidebar that shows two random photos from our flickr account, using their javascript widget. This was a great way to get things going, but now we’ve developed slightly more involved needs and I’ve had to come up with a custom solution.
Getting the list of photos
You need a flickr API key, which is quick & easy to get. Then wget & cron to get ‘em: wget --quiet 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOUR_API_KEY&user_id=YOUR_USER_ID&tags=website&per_page=500' -O photos.xml
Note that this includes a tags argument. The thing that pushed me to switch the workflow was the desire to be able to upload photos to our flickr account that don’t necessarily fit into the sidebar format, such as panoramics. To handle this, everything that belongs on the website gets the tag website, and we only fetch those ones. We’ve also talked about just getting landscape oriented photos, but haven’t implemented that.
I’m running this daily, which is plenty often to update the available photo list. I believe this gets the newest 500, which seems more than adequate, particularly since we don’t have close to 500 photos yet.
Parsing the list & generating the HTML
PHP5’s SimpleXML is pretty nice — here’s what we’re doing:
try {
$xml = new SimpleXMLElement(file_get_contents('photos.xml'));
$number_of_photos = count($xml->photos->photo);
$displayed_photos = array();
array_push(
$displayed_photos,
$xml->photos->photo[rand(0, $number_of_photos - 1)]);
array_push(
$displayed_photos,
$xml->photos->photo[rand(0, $number_of_photos - 1)]);
foreach ($displayed_photos as $photo) { ?>
<div>
<?php
print "<a href=\"http://www.flickr.com/photos/8562013@N07/" .
$photo['id'] . "\"><img src=\"http://farm" . $photo['farm'] .
".static.flickr.com/" . $photo['server'] . "/" . $photo['id'] . "_" .
$photo['secret'] . "_m.jpg\" alt=\"" . $photo['title'] . "\" /></a>";
?>
</div>
<?php
}
} catch (Exception $e) {
error_log("flickr badge had some troubles: " .
$e->getMessage());
}
This snippet takes my laptop less than 1/20th of a second to run from the command line, which suits me fine. The actual code sits in page.tpl.php.
Flickr’s API docs, in particular the API Explorer, were awful handy in figuring this all out.
