In this code example, we will show how you can use some simple PHP scripts to cache API data to your local server. This can be useful to increase the speed of your app as you do not need to call the API each time your app needs to load the same data.
The script checks the local cache automatically when loaded, and will update the data after the set expiration time. You can customize the expiration interval to suit your needs. Let’s jump in:
First we need to define where the local .json file should be stored on the server, which will cache the data in JSON format. In this case we are saving to the same directory as the PHP file. For example, if you are hosting your PHP file in the /public_html/ folder, your cache file will be stored in the same location.
// Path to store your cache text file $filePath = "quotes.json";
Next we need to set the API source and set how long the cache file should be stored. This value is expressed in seconds and by default is set to refresh the quotes every hour. In this example we are using the Random Quotes API Batch call, which provides you with 50 items that you can work with in your app. Customize this call using the steps in our documentation.
// ViewBits API URL $url = "https://api.viewbits.com/v1/zenquotes?mode=batch"; // Cache update time in seconds $expireTime = (60 * 60); // Update every hour
The above lines are the only items that need to be customized. The next block of code will check for the local file, read the last updated time, and refresh the data if necessary.
// Check whether data needs to be updated if( (filemtime($filePath) + $expireTime) < time() ){$isStale = true;} // Quotes are expired and need to be refreshed if($isStale === true) { // Get API Response $json = file_get_contents($url); // Verify cache file exists $cacheFile = fopen($filePath, "w"); // Write the new data to file and close if($cacheFile && $json) { fwrite($cacheFile, $json); fclose($cacheFile); } }
After checking the expiration time, the quotes array can be loaded into a local variable for you to manipulate using the json_decode function:
// Decode and assign the quotes to an array $jsonArr = json_decode(file_get_contents($filePath),true); // Shuffle to get a random value at 0 shuffle($jsonArr); // Grab Individual Entries and Output Data echo $jsonArr[0]['q']."<br>"; echo $jsonArr[0]['a']."<br>"; echo $jsonArr[0]['h']."<br>"; // Output Full Array print_r($jsonArr);
That’s it! With this simple code, you can improve the performance of your app and ensure you have data in the event that the ViewBits API becomes temporarily unavailable. The completed code example is provided below:
// Path to store your cache text file $filePath = "quotes.json";
// ViewBits API URL
$url = "https://api.viewbits.com/v1/zenquotes?mode=batch";
// Cache update time in seconds
$expireTime = (60 * 60); // Update every hour
// Check whether data needs to be updated
if( (filemtime($filePath) + $expireTime) < time() ){$isStale = true;}
// Quotes are expired and need to be refreshed
if($isStale === true)
{
// Get API Response
$json = file_get_contents($url);
// Verify cache file exists
$cacheFile = fopen($filePath, "w");
// Write the new data to file and close
if($cacheFile && $json)
{
fwrite($cacheFile, $json);
fclose($cacheFile);
}
}
// Decode and assign the quotes to an array
$jsonArr = json_decode(file_get_contents($filePath),true);
// Shuffle to get a random value at 0
shuffle($jsonArr);
// Grab Individual Entries and Output Data
echo $jsonArr[0]['q']."<br>";
echo $jsonArr[0]['a']."<br>";
echo $jsonArr[0]['h']."<br>";
// Output Full Array
print_r($jsonArr);