如何用php制作api请求缓存?
有一个代码api url,它是json格式的输出。我需要缓存我的json结果或其他解决方案。因为我的页面在访问新用户时会再次调用api,页面打开速度会出现问题。我怎样才能做到 我的代码:如何用php制作api请求缓存?,php,json,api,caching,Php,Json,Api,Caching,有一个代码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_outpu
<?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>';
}
?>
如果您想使用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);
只需将其缓存在文件中:
$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谢谢您的回答。我需要不带memcache的缓存json结果。我无法在我的主机上使用memcache。