Skip to content

Instantly share code, notes, and snippets.

@ScottPhillips
Created July 18, 2012 23:52
Show Gist options
  • Select an option

  • Save ScottPhillips/3139774 to your computer and use it in GitHub Desktop.

Select an option

Save ScottPhillips/3139774 to your computer and use it in GitHub Desktop.
Cache Remote JSON Feed
HOW IT WORKS
The function takes two arguments:
The $cache_file argument stores the server location of the cache file you wish to use. By default it will look for api-cache.json in the same directory as the script using this function.
The $expires argument will store the time between each API request. By default a new API request will be made every 2 hours.
You’ll need to create the cache file with CHMOD 777 permissions before this function will work. The function will check to see if the cache file exists using file_exists(), throwing an error message if it does not. If the cache file exists, the script will check to see if it’s empty using file_get_contents(). If it is empty an initial API request is made and the results are stored as JSON in the cache file using file_put_contents(). If the cache file exists and is not empty the script will check the last time the file was modified using filectime(). If it was modified longer than the $expires time an API request is made and the file is updated.
<?php
/**
* API Request Caching
*
* Use server-side caching to store API request's as JSON at a set
* interval, rather than each pageload.
*
* @arg Argument description and usage info
*/
function json_cached_api_results( $cache_file = NULL, $expires = NULL ) {
global $request_type, $purge_cache, $limit_reached, $request_limit;
if( !$cache_file ) $cache_file = dirname(__FILE__) . '/api-cache.json';
if( !$expires) $expires = time() - 2*60*60;
if( !file_exists($cache_file) ) die("Cache file is missing: $cache_file");
// Check that the file is older than the expire time and that it's not empty
if ( filectime($cache_file) < $expires || file_get_contents($cache_file) == '' || $purge_cache && intval($_SESSION['views']) <= $request_limit ) {
// File is too old, refresh cache
$api_results = indeed_api_request();
$json_results = json_encode($api_results);
// Remove cache file on error to avoid writing wrong xml
if ( $api_results && $json_results )
file_put_contents($cache_file, $json_results);
else
unlink($cache_file);
} else {
// Check for the number of purge cache requests to avoid abuse
if( intval($_SESSION['views']) >= $request_limit )
$limit_reached = " <span class='error'>Request limit reached ($request_limit). Please try purging the cache later.</span>";
// Fetch cache
$json_results = file_get_contents($cache_file);
$request_type = 'JSON';
}
return json_decode($json_results);
}
<?php
/**
* Format a basic job listing in HTML5
*/
function indeed_job_results( $api_results = NULL, $search = NULL ) {
if( !$api_results ) return false;
$total = count($api_results);
$search = ( $search ) ? " found for &ldquo;<strong>$search</strong>&rdquo;" : "";
$html = "<section class='jobs'>";
$html .= "<header>";
$html .= "<h2>$total jobs$search</h2>";
$html .= "</header>";
foreach ( $api_results as $job ) {
$date = explode(' ', $job->date);
$formattedDate = $date[2] . ' ' . $date[1] . ', ' . $date[3];
$html .= "<article>";
$html .= "<h3><a href='{$job->url}' target='_blank'>{$job->jobtitle}</a></h3>";
$html .= "<p class='details'>{$job->formattedLocation} <em>&ndash;</em> $formattedDate</p>";
$html .= "</article>";
}
$html .= "</section><!--// end .jobs -->";
return $html;
}
//Using the function in practice is simple:
$api_results = json_cached_api_results();
$jobs_output = indeed_job_results( $api_results, 'Google' );
@floydlord
Copy link

Thank you for your code because it's helpful for my rooftop snipers website and I can solve my issues.

@securemailpro
Copy link

Really well-written! The structure and clarity of this post make it a pleasure to read. I learned a lot from your examples and tips. Looking forward to more posts that dive this deep. digital connect mag

@securemailpro
Copy link

Loved this! The unsent project colors and their meanings are so unique. It’s amazing how a simple color choice can convey feelings we struggle to put into words. old unsent project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment