Sunday, May 9, 2010

APC caching for Web services - Yahoo

error_reporting(E_ALL);

$request =  'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&results=1';

// Number of seconds until the cache gets stale
$cache_timeout = 7200;

// Check the cache
$response = request_cache($request, $cache_timeout);

if ($response === false) {
 die('Request failed');
}

// Output the XML
echo htmlspecialchars($response, ENT_QUOTES);

// This is the main caching routine. More robust error checking should
// be implemented.

function request_cache($url, $ttl) {
 if(!$xml = apc_fetch($url)) {
  $xml = file_get_contents($url);
  if ($xml === false) return false;
  apc_store($url,$xml, $ttl);
 }
 return $xml;
}

?>

No comments: