How to Variable Cache in PHP
I am looking at trying to cache variables in PH开发者_StackOverflow中文版P from a JSON file. Is there anyone that knows of a good tutorial or can provide an example?
Save variable to file cache:
file_put_contents('cache.txt', json_encode($variable));
Read cache into variable:
$variable = json_decode(file_get_contents('cache.txt'));
Memcached is your best bet. It will save any serializable data in a very fast cache. You can find a tutorial at:
http://php.net/manual/en/memcache.examples-overview.php
It is lightning quick and has many other features that makes it better than just saving a txt file to the server.
$memcache->set('key', $jsonstring, false, 10)
and
$get_result = $memcache->get('key');
A simple approach is:
function getMyJson()
{
$data = apc_fetch('my_json', $wasCached);
if ($wasCached) {
return $data;
}
$data = json_decode(file_get_contents('/path/to/data.json'));
apc_store('my_json', $data);
return $data;
}
This uses APC's cache but you could work similarly with memcached, redis etc.
精彩评论