Reputation: 343
There is a code api url and it is output json format. I need cache my json result or different solution. Because my page when visiting new user it calling api again and page opening speeds consists of problems. How can i make it?
My Code:
<?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>';
}
?>
Upvotes: 0
Views: 3963
Reputation: 1970
Just cache it in a file :
$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);
With this example the cache is infinite, you can just remove the cache file with a cron task or check the file creation timestamp with the php function filemtime to set a time limit for cache. You can cache it in DB too with a table with 3 fields : key, value (json), timeout
Upvotes: 0
Reputation: 21
If you want to use memcache as your cache service, you can try something like this:
$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);
Upvotes: 2