Simple File Caching Script
August 6, 2010 2:24 pmOn a recent project, I needed a quick, easy and simple caching function for XML files, so whipped up this little function.
How it works
It takes:
- The URL of the file / XML you need to cache
- The cache file, if one is not specified, it creates and uses “temp.txt”
- The amount of time to cache the file, if one is not specified, it uses 12 minutes (you can change this to whatever you would like
The Function
[markdown]
“`php
function cacheFeed( $feed, $cacheFile=’temp.txt’, $cacheTime=12 ) {
$debug = false; // Set this to true for output and debuging
if ( $debug ) echo “Begining feed”;
if ( $debug ) echo “File Exists: “;
// Make sure the file is there
if ( file_exists($cacheFile) ) { // Make sure the file is there
if ( $debug ) echo “True”;
// If the file modified time is outside of the cache time OR the file size is 0 (empty file)
if ( strtotime(‘+’.$cacheTime.’ minutes’,filemtime($cacheFile)) < strtotime("now") || !filesize($cacheFile) ) {
// Set up curl and options
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $feed );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_HEADER, 0);
$data = curl_exec( $ch );
curl_close( $ch );
if ( $data != "" ) {
if ( $debug ) echo "Recieved Feed";
file_put_contents($cacheFile,$data);
if ( $debug ) echo "Writing to Cache File";
}
} else {
$data = file_get_contents($cacheFile);
}
} else {
if ( $debug ) echo "False";
$f = fopen($cacheFile,'x'); // Create file to write to.
if ( $f ) {
fclose($f); // No need to keep it open
$data = $this->cacheFeed($feed,$cacheFile,$cacheTime);
} else {
$data = false;
}
$data = cacheFeed($feed,$cacheFile,$cacheTime);
}
return $data;
}
“`
[/markdown]
Example Usage
[markdown]
“`php
include_once( ‘cacheFeed.php’ );
$cacheFile = ‘cache/cacheFile.xml’;
$feed = ‘http://linktoyour.com/XMLfile.xml’;
$data = cacheFeed($feed, $cacheFile, 30);
$xml = new SimpleXMLElement($data);
“`
[/markdown]
Thats it, pretty simple to use. I hope someone gets some use out of this!