Caching Tweets with PHP

This post is old. It may contain broken links, missing images and incorrect information.

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;
Jack Barber, freelance web developer based in Whitby, UK

Written By

I'm a freelance web developer based in Whitby, UK. I built my first website using GeoCities, and learned to write HTML and CSS using Notepad. Web technology has come a long way since then, as have my web development skills!

These days I love helping my clients make the most of the internet. I provide design, development, marketing and IT support services, forming long-term partnerships with my clients.

Connect With Me

Posted in Uncategorized