Creating a cache file in php for API requests

by Php Ninza on August 21, 2009


Web 2.0 was all about mashups and data api’s !, Some of the popular ones are google search api , twitter api etc.

All API’s have some rate-limiting , For example Twitter API has a rate limit of 150 requests per hour ! , Yahoo API and Google API’s have a daily limit on their requests.

The ultimate method of getting over this API request limit is to make a cache method which stores all data that is coming from API , Which you can refresh hourly, weekly or daily !

That’s why i created a small function to store the API data in a xml cache file , Which can be later on retrieved to get data.Find that function below, Most of the functionality is explained in the comments , If anything is not clear contact me via contact page.

< ?php

function get_yahoo_data_cached($query, $zip) {
    // Rewrite by Julius Beckmann 

    // Remove dangerous chars
    $query_safe = str_replace(array('.','/'), '_', $query);
    $zip_safe = str_replace(array('.','/'), '_', $zip);

    $cache_filename = "cache/$query_safe-$zip_safe.xml";
    $time_expire = time() + 24*60*60; // Expire Time (1 Day)

    // Check file change time
    if(filectime($filename) <= $time_expire) {
        // File is too old, refresh cache
        $xml = get_yahoo_data($query, $zip);
        // Remove cache file on error to avoid writing wrong xml
        if($xml)
            file_put_contents($cache_filename, $xml);
        else
            unlink($cache_filename);
    }else{
        // Fetch cache
        $xml = file_get_contents($cache_filename);
    }

    return $xml;
}

?>

Safe rewrite of the function by Julius Beckmann
This function creates a cache file for yahoo api requests , here we are using get_yahoo_data() function to fetch data from yahoo api which is a custom function for extracting data from yahoo api and throwing that in xml output format.

If we do a small synopsis of the above function we can see that it uses 2 variables to store cache , $filename stores the cache file and $file_log_name stores the last update time for that cache !

Technorati Tags: ,,

Technorati Tags: , ,

  • inversechi
    This helped me getting started with writing a simple caching plugin for API's to use within codeigniter - thank you :)
blog comments powered by Disqus

Previous post:

Next post:

BidVertiser