Here's a simple example using PHP to access and cache requests to the Flickr API. This is the method I use for the
flickr world map. Two very useful and easy to use php libraries are need to make this example work,
MiniXML and
Cache Lite. Cache Lite is a PEAR extension but you can simply download the source and include "Lite.php" as I've done in the example below.
Grab the
code or see the
result.
<?php
// Include cachelite
require_once('cachelite/Lite.php');
$cacheoptions = array(
// The directory you want to store the cache files in.
'cacheDir' => '/cache/',
// Length of time to cache requests in seconds. "86400" = 24 hours.
'lifeTime' => 86400
);
// include minixml
require_once('minixml.inc.php');
//Create a flickr rest url. Update the method and various parmeters
// below to match the request you want to make to the API.
$base = 'http://www.flickr.com/services/rest/';
$query_string = '';
$params = array(
'method' => 'flickr.photos.search',
'api_key' => 'your api key',
'tags' => 'sunrise',
'tag_mode' => 'all',
'per_page' => '1',
'sort' => 'date-taken-desc',
);
foreach ($params as $key => $value) {
$query_string .= "$key=" . urlencode($value) . "&";
}
$url = "$base?$query_string";
// Check cache to see if this url already exsits.
// If not send the url request to flickr and cache the responce.
$Cache_Lite = new Cache_Lite($cacheoptions);
if ($xml = $Cache_Lite->get($url)) {
} else {
$xml = file_get_contents($url);
$Cache_Lite->save($xml);
}
// Check that the xml has been loaded.
if ( $xml ) {
// Parse the xml using minixml.
$parsed = new MiniXMLDoc();
$parsed->fromString($xml);
$root =& $parsed->getRoot();
// Get the xml rsp element and stat attribute.
$rsp =& $root->getElement('rsp');
$stat = $rsp->attribute('stat');
// Check that the api request was succesful.
if ($stat != "fail") {
/*
In this example we're using the search method but you would
have different elements and attrributes depending on the
method you called above. Check the example xml responces
in the flickr api documentation for what xml elements and
atributes you can expect to see returned.
*/
// Get the "photo" xml element.
$photo =& $root->getElement('photo');
// Check the "photo" element was found.
if ( $photo ) {
// Load the "photo" attributes into vars for later use.
$photoid = $photo->attribute('id');
$secret = $photo->attribute('secret');
$server = $photo->attribute('server');
$title = $photo->attribute('title');
// Turn the photo attributes into a flickr image url.
$photourl = "http://photos" . $server . ".flickr.com/" . $photoid . "_" . $secret . "_m.jpg";
// The result! Show the latest sunset photo.
echo("<img src='$photourl' />");
} else {
echo("The photo element was not found.");
}
} else {
echo("Requested failed. Check the method and parameters sent.");
}
} else {
echo("Unable to connect and load an xml responce from flickr.");
}
?>