有一个代码api url,它是输出json格式。我需要缓存我的json结果或不同的解决方案。因为我的页面在访问新用户时再次调用api并且页面打开速度包含问题。我该怎么做?
我的代码:
<?php
$jsonurl = 'http://api.site.com/deal/browse.html?apiKey=VN43U6&p=2';
$json = file_get_contents($jsonurl, 0, null, null);
$json_output = json_decode($json);
foreach ($json_output->deals as $objects) {
$title = $objects->title;
echo '<h5 class="coupon-title">' . $title . '</h5>';
}
?>
答案 0 :(得分:0)
如果你想使用memcache作为你的缓存服务,你可以尝试这样的事情:
$memcache = new Memcache;
$memcache->connect("localhost", 11211);
$hash = hash('sha256', $jsonurl);
$json = $memcache->get($hash);
if (!$json) {
$json = file_get_contents($jsonurl, 0, null, null);
$memcache->set($hash, $json, false, strtotime("+1 day"));
}
$json_output = json_decode($json);
答案 1 :(得分:0)
将其缓存在文件中:
$cache_json='yourfilename.json';
if(!is_file(cache_json)){
$json = file_get_contents($jsonurl, 0, null, null);
file_put_contents($cache_json,$json);
}
else{
$json = file_get_contents($cache_json);
}
$json_output = json_decode($json);
使用此示例缓存是无限的,您可以使用cron任务删除缓存文件,或使用php函数filemtime检查文件创建时间戳以设置缓存的时间限制。 您也可以使用包含3个字段的表将其缓存在DB中:key,value(json),timeout