Skip to content

Instantly share code, notes, and snippets.

@erwstout
Created November 15, 2016 15:41
Show Gist options
  • Save erwstout/13369353c73baf29ef31299d5f14bc49 to your computer and use it in GitHub Desktop.
Save erwstout/13369353c73baf29ef31299d5f14bc49 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