UPDATE: this code will no longer work due to the v1 api being deactivated, but I’ve modified the script to work with the v1.1 api. You can find out how to get the cache working on this blog post.

If you’ve got a Twitter feed on your site that pulls tweets directly from Twitter’s API, you’ve probably noticed that quite often your tweets won’t display. Twitter’s API receives so many requests that quite often it’s unreliable. So much so that I wrote a little PHP script that caches tweets. It’s actually ridiculously simple, all it does it cache the feed, and refreshes if the cache is older than 10 minutes. If the refresh fails, it simply serves up the old cache. So even if twitter goes down, your site isn’t affected.

Note: you’ll need to create a cache folder in the same directory as the script, and a twitter-cache file inside that in order to avoid first-run errors. The script should create the file automatically if it doesn’t exist (albeit returning a warning), but you’ll need to make sure the folder exists first.

This code is also available on github.

Simply save that as a script, and call it just like you do with your standard Twitter call. For example in javascript & jQuery: