Remote file caching with interval updates with PHP

Question:

I'm developing a news portal and I'm using a weather forecast API . The problem is that every time people open the page, PHP downloads the JSON from the API , and this ends up interfering with the page's loading speed.

In order to solve this problem and save bandwidth, I thought I would cache this JSON and download updates every 15 minutes, but I have no idea where to start.

Can you help me? Thank you in advance.

Answer:

What you need is to use a caching system like memcached . In your code where you get the JSON you do a conditional check that sees if this JSON is already stored in the cache, if it is you just get it from there (which is an instantaneous operation since usually the cache will store it in RAM), if the JSON is not present you get it from the external server and cache it. In code it will look something like this:

$memcached = new Memcached('pool');

$data = $memcached->get('alguma_previsao');
if ($data === Memcached::RES_NOTFOUND) { // dados não estão no cache
    $data = getJSONdoServidorExterno(); // aqui você pega o JSON como já faz normalmente

    $memcached->add('alguma_previsao', $data, 60 * 15); // armazena o JSON por 15 minutos no cache (60 segundos * 15)
}
$jsonFinal = $data; // aqui você tem o JSON de que precisa
Scroll to Top