Skip to content

Instantly share code, notes, and snippets.

@fagnersutel
Forked from erwstout/cache-json.php
Created May 31, 2018 20:32
Show Gist options
  • Save fagnersutel/232c125ce5ea70bbf210f6228202bf36 to your computer and use it in GitHub Desktop.
Save fagnersutel/232c125ce5ea70bbf210f6228202bf36 to your computer and use it in GitHub Desktop.
Write JSON file and cache it.
<?php
/**
* Write an array to a JSON file. Replace $data with your array,
* and skip JSON encoding if you already have JSON
*/
function write_data_to_file( $filename ) {
$json = file_get_contents( 'http://path.to/external-site/file.json');
$time = time();
file_put_contents( $filename, $json );
}
$filename = 'data.json';
if ( file_exists( $filename ) ) {
$file_time = filemtime( $filename );
$expire = 30; // Time in seconds to cache the file for
if ( $file_time < ( time() - $expire ) ) {
// if expired, overwrite file
write_data_to_file( $filename );
}
} else {
// if file does not exist, write to file
write_data_to_file( $filename );
}
header('Content-Type: application/json');
$file_data = file_get_contents( $filename );
echo $file_data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment