0

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>';
}
?>
0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for answer. I need cache json result without memcache. I can't using memcache on my hosting.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.