Content cache an retrieve with PHP

Website with huge database is often slower when pulling data from another feed. It’s a total harass when hitting your database again and again after knowing it’s not changing so frequently. This snippet can query after the database updates. And it fetches data from cached content when database is not synchronized.

 

// JavaScript Document$TWITTER_FOLLOWERS_FILE_NAME = ‘twitter-followers.txt’;

$TWITTER_FOLLOWERS_URL = ‘http://twitter.com/users/show.json?screen_name=username’;

 

$TWITTER_FOLLOWERS = get_content($TWITTER_FOLLOWERS_FILE_NAME,$TWITTER_FOLLOWERS_URL,3,’format_followers’,array(‘file’=>$TWITTER_FOLLOWERS_FILE_NAME));

/* utility function */

function format_followers($content,$args) {

$content = json_decode($content);

$twitter_subscribers = $content->{‘followers_count’};

if($twitter_subscribers) {

$twitter_subscribers = number_format($twitter_subscribers,0,”,’,');

file_put_contents($args['file'],$twitter_subscribers);

return $twitter_subscribers;

}

}

 

This function is from basic language. Though it’s very handy for caching and retrieves content from databases. So don’t hesitate to use such conditions.

 

// JavaScript Documentfunction get_content($file,$url,$hours = 24,$fn = ”,$fn_args = ”) {

$current_time = time(); $expire_time = $hours * 60 * 60; $file_time = filemtime($file);

//decisions, decisions

if(file_exists($file) && ($current_time – $expire_time < $file_time)) {

return file_get_contents($file);

}

else {

$content = get_url($url);

if($fn) { $content = $fn($content,$fn_args); }

$content.= ”;

file_put_contents($file,$content);

return $content;

}

}

 

function get_url($url) {

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);

$content = curl_exec($ch);

curl_close($ch);

return $content;

}

 

This code pulls data from twitter, parses the data, and caches it for three hours.

No related posts.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.