Code Example: Cache API Data to Local .txt File with PHP

In this code example, we will show how you can use some simple PHP scripts to cache a batch of ZenQutoes to your local server. This can be useful to increase the speed of your app as you do not need to call the ZenQuotes API each time your app needs to load a random quote.

The script checks the local cache automatically when loaded, and will update the data if expired. You can customize the cache update interval to suit your needs. Let’s jump in:

First we need to define where the local .txt 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.txt";

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. The “ZenQuotes.io/api/quotes” call provides you with 50 random quotes. Customize this call using the steps in our documentation.

// ZenQuotes API URL
$url = "https://zenquotes.io/api/quotes";

// 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 quotes 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 ZenQuotes API becomes temporarily unavailable. Completed code example is provided below:

<?php

// ZenQuotes.io PHP Local .txt Cache Example
// Use this snippet to store a batch of quotes on your local server
// Code will auto update cache based on your input time

// Path to store your cache text file
$filePath = "quotes.txt";

// ZenQuotes API URL
$url = "https://zenquotes.io/api/quotes";

// 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;}

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 Entry and Data
echo $jsonArr[0]['q']."<br>";
echo $jsonArr[0]['a']."<br>";
echo $jsonArr[0]['h']."<br>";

// Output Full Array
print_r($jsonArr);
  
?>

Subscribe