prinsich / php-excel-reader

Automatically exported from code.google.com/p/php-excel-reader
0 stars 0 forks source link

Support for caching results (patch included) #12

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I don't think it's a good idea to process the spreadsheet file over and over 
again, especially as it 
may not change very frequently.

Here's a little function to cache the results of the spreadsheet read as a PHP 
object. Make sure 
you create the cache directory and make sure it can be written to.

best,
matt

function Cached_Spreadsheet($filename) {
    $cache_dir = './cache';     //set to null to disable cache
    $xlsmtime = filemtime($filename);
    $cached = false;

    // If CACHE ENABLED
    if ($cache_dir != '' && file_exists($cache_dir)) {
        $cache_file = $cache_dir . '/xlscache_' . md5($filename);
        $timediff = @($xlsmtime != filemtime($cache_file));
        if ($timediff && file_exists($cache_file)) {
            // cached file is fresh enough, return cached array
            $result = unserialize(join('', file($cache_file)));
            // set 'cached' to 1 only if cached file is correct
            if ($result) $cached = true;
        } else {
            // cached file is too old, create new
            $result = new Spreadsheet_Excel_Reader($filename, false);
            $serialized = serialize($result);
            if ($f = @fopen($cache_file, 'w')) {
                fwrite ($f, $serialized, strlen($serialized));
                fclose($f);
            }
            if ($result) $cached = false;
        }
    } else {
        // If CACHE DISABLED >> load and parse the file directly
        $result = new Spreadsheet_Excel_Reader($filename, false);
        if ($result) $cached = false;
    }

    if ($cached) echo "<!-- cached result -->\n";

    // return result
    return $result;
}

$xls = Cached_Spreadsheet("example.xls");

Original issue reported on code.google.com by matt.sep...@gmail.com on 11 Mar 2009 at 3:53

Attachments:

GoogleCodeExporter commented 9 years ago
timediif wil work correct by this

$timediff = @($xlsmtime <= filemtime($cache_file));

Original comment by eugene.f...@gmail.com on 7 Feb 2010 at 1:34