<coded>


How to cache JSON data and keep your API requests low

May 19, 2022

Just a small PHP script if you work with API data in your project and want to keep requests low. We cache the data and read out of temp file most of the time.

1. Set your cache file

First step we define the file where we want to store the data.

<?php
$cache_file = "projectfolder/cache/json_cache.txt";

2. Check if we need the request

We create a simple if/else whether to check if the file is older than 3600 seconds (= 1 hour) or not. Or if the file doesn't exist yet. Only if on of this requirements are met, we make the request on the api.

if((time()-filemtime($cache_file) > 3600) || !file_exists($cache_file)) {
    ...
}
else {
    ...
}

3. Full script

For my example I use Google's Places API which is basically the thing where you can get user reviews from your or other companies. We bring back the string to json with json_decode.

We open our file with fopen and write our json data with fwrite.

Same goes for reading open file and then get data with fread and put it in the same variable as we would if we do a real request.

Here's the complete script:

<?php
$cache_file = "projectfolder/cache/json_cache.txt";

if(!file_exists($cache_file) || (time()-filemtime($cache_file) > 21600)) {
    $api_data = file_get_contents("https://maps.googleapis.com/maps/api/place/details/json?key=YOUR_API_KEY&placeid=YOUR_PLACES_ID");
    $data = json_decode($api_data);

    $fx = fopen($cache_file, "w+");
    $write = fwrite($fx, $data);
    fclose($fx);
}
else {
    $fp = fopen($cache_file, "r");
    $result = fread($fp, filesize($cache_file));
    $data = json_decode($result);
    fclose($fp);
}

print_r($data);
?>
Did you find this useful? Please rate this post: