Created
November 15, 2016 15:41
-
-
Save erwstout/13369353c73baf29ef31299d5f14bc49 to your computer and use it in GitHub Desktop.
Write JSON file and cache it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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