Amit Dhamu

Software Engineer

Cacheable Tweets

Since Twitter have introduced Rate Limiting for their REST API, the tweets I show across my site have broken and seem to work only when they want to.

The function below should help you overcome this issue.

function getTweets($screen_name) {
    $tweets = array();
    $local_file = '/cache/tweets.json';
    $api_url = '".$this->twitter_screename."&count=10';

    // If cached .json file exists
    if(is_file($local_file)) {
        // Work out when the cached file was last updated
     $cache_duration = strtotime('now') - filemtime($local_file);

        // If this is more than 10 minutes, go and refetch from API
 if($cache_duration > 600) {
        $get_tweets = file_get_contents($api_url);

                // Put the contents from the fresh request into the cached file
     file_put_contents($local_file, $get_tweets);
  } else {
                // Get the local .json feed as it's been less than 10 minutes
      $get_tweets = file_get_contents($local_file);
    } else {
        // File doesn't exist, so query the API and create the cache file populating it with the results
    $get_tweets = file_get_contents($api_url);
    file_put_contents($local_file, $get_tweets);
    $tweets = json_decode($get_tweets);
    return $tweets;

$tweets = getTweets('YOUR_TWITTER_SCREEN_NAME'); // an array of your tweets

twitter api / user timeline / json / cache / php

← Mixins in LESS Scroll To Position →