d
Amit DhamuSoftware Engineer
 

Cacheable Tweets

3 minute read 00000 views

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 = [];
    $local_file = '/cache/tweets.json';
    $api_url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=' . $screen_name . '&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