How to implement a Yahoo currency cache?

0 votes
asked Jun 21, 2010 by unix-man

I have a Yahoo currency script in my site but they are taking too much time to load and are slowing my site. How can I cache them and refreshing cache every 3600 minutes?

3 Answers

0 votes
answered Jun 21, 2010 by yann-ramin

You need some place to store these results. MySQL is a popular choice, but if the data does not need to stick around or have historical values, using memcache would be easier. Depending on your host, both of these options may be available.

0 votes
answered Jun 21, 2010 by sarfraz

Also, rather than fgets which reads file line by line rather slower and since you are not manipulating a line, you should consider using file_get_contents function instead.

0 votes
answered Jun 21, 2010 by ariefbayu

The idea is:

  • create some sort of cache dir and set the defined cache age
  • then, at the very beginning of your function, check for cache
    • if it exists, check it's age.
      • If within range, get it
    • if cache too old
      • use live data and set that data into cache file.

Something like this should do the trick:

define(CACHE_DIR, 'E:/xampp/xampp/htdocs/tmp');
define(CACHE_AGE, 3600);
 * Adds data to the cache, if the cache key doesn't aleady exist.
 * @param string $path the path to cache file (not dir)
 * @return false if there is no cache file or the cache file is older that CACHE_AGE. It return cache data if file exists and within CACHE_AGE 
function get_cache_value($path){
        $now = time();
        $file_age = filemtime($path);
        if(($now - $file_age) < CACHE_AGE){
            return file_get_contents($path);
        } else {
            return false;
    } else {
        return false;

function set_cache_value($path, $value){
    return file_put_contents($path, $value);

function kv_euro () {
    $path = CACHE_DIR . '/euro.txt';

    $kveuro = get_cache_value($path);
    if(false !== $kveuro){
        echo "\nFROM CACHE\n";
        return round($kveuro, 2);
    } else {
        echo "\nFROM LIVE\n";
        $from   = 'EUR'; /*change it to your required currencies */
        $to     = 'ALL';
        $url = ''. $from . $to .'=X';
        $handle = @fopen($url, 'r');

        if ($handle) {
            $result = fgets($handle, 4096);
        $allData = explode(',',$result); /* Get all the contents to an array */
        $kveuro = $allData[1];
        set_cache_value($path, $kveuro);
        return $kveuro;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter