erwstout
11/15/2016 - 3:41 PM

Write JSON file and cache it.

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;