Jack Barber Design & Technology

01947 878108 info@jackbarber.co.uk

Caching Tweets with PHP

On a number of recent projects, I've been incoroporating the site owner/company's latest tweet using jQuery.  However, whilst it's unlikely that these sites would exceed Twitter's API request limited, I wanted to create an alternative script which would cache the latest tweet for a specified time and serve the cached version to all of the site's visitors, greatly reducing the number of API requests.

The solution I developed is below.  I've commented in the code to explain what's going on, but basically there are four stages:

  1. Define the cache location (writeable directory and plain text file)
  2. Check if a cached tweet existis and if not, create one
  3. Check how long has passed since the previous cache
  4. If more than the defined time, generate a new cache and return the newest tweet, if less, return the existing cache

The script overwrites the existing cache and includes the time at which it is generated, so that the next time the function is called it can work out whether it should look for a new tweet or not.

Here's the solution:

//**YOU NEED TO EDIT THESE**//
$Twitter = 'YOUR_USERNAME';
$dir = './CACHED/DIR';
$file = './CACHED/DIR/FILENAME.txt';

//**Get Current Time**//
$now = date('Y-m-d H:i');

//**Check if Cache Exists**//

if(!file_exists($file)){
//**If Not, Create Directory and First Cached Tweet**//
    if(!is_dir($dir)){
        mkdir($dir,0755);
    }
    $fh = fopen($file, 'w');
   
    $json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline/$Twitter.json?count=1&callback=?", true);
    $decode = json_decode($json, true);
   
    $time = $decode[0]['created_at'];
    $tweet = $decode[0]['text'];
   
    $tweetData = $now."\r".$time."\r".$tweet;
   
    $fp = fopen($file, 'w');
    fwrite($fp, $tweetData);
    fclose($fp);
}

//**Get Cached File Contents**//
$contents = file_get_contents($file);

$lines = preg_split('/\r/', $contents);

$date1 = new DateTime($lines[0]);
$date2 = new DateTime($now);
$interval = $date1->diff($date2);
$mins = $interval->i;

//**If More Than 1 Hour Has Passed...**//
if($mins>60){
    $json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline/$Twitter.json?count=1&callback=?", true);
    $decode = json_decode($json, true);
   
    $time = $decode[0]['created_at'];
    $tweet = $decode[0]['text'];
   
    $tweetData = $now."\r".$time."\r".$tweet;
   
    $fp = fopen($file, 'w');
    fwrite($fp, $tweetData);
    fclose($fp);
   
    //**Return New Tweet**//   
    $return = $time."\r".$tweet;
}else{
    //**Return Cached Tweet**//
    $return = $lines[1]."\r".$lines[2];
}

echo $return;