Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.