Retrieving a Twitter Stream

Recently, Twitter shutdown version 1.0 of their API, completely switching to version 1.1. Among other things, this version of their API requires authentication to retrieve Tweets, even from a public timeline.

As you may have noticed, the sidebar on the right has a few of my recent Tweets, which meant I had to replace my old, simple piece of code with the more complicated version, which you are free to insert into your own site.

Think of it as a gift. From me, to you. And maybe Twitter, as well. Which means you're not sure who to write the thank you note to, are you?

Here is the more complicated version:

* Get the latest tweets for a particular user
* @param string consumerKey The consumer key provided by Twitter
* @param string consumerSecret The consumer secret provided by Twitter
* @param string screenName The screen name for the user to retrieve tweets for
* @param int count The number of recent tweets to retrieve
* @param string cacheFile The path to the file where the Twitter feed is cached once a minute * @return array(string => string) An array of date/HTML pairs
function getTweets($consumerKey, $consumerSecret, $screenName, $count, $cacheFile)
$encodedKey = urlencode($consumerKey);
$encodedSecret = urlencode($consumerSecret);
$authorization = base64_encode($encodedKey . ":" . $encodedSecret);

if(!file_exists($cacheFile) || (filemtime($cacheFile) < (time() - 60)))
$obtain = curl_init();

curl_setopt($obtain, CURLOPT_URL, "");
curl_setopt($obtain, CURLOPT_ENCODING, "gzip");
curl_setopt($obtain, CURLOPT_HTTPHEADER, array("Authorization: Basic " . $authorization, "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"));
curl_setopt($obtain, CURLOPT_POST, true);
curl_setopt($obtain, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($obtain, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($obtain);

$details = json_decode($data);

$request = curl_init();

curl_setopt($request, CURLOPT_URL, "" . $screenName . "&count=" . $count);
curl_setopt($request, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $details->access_token));
curl_setopt($request, CURLOPT_ENCODING, "gzip");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($request);

file_put_contents($cacheFile, $data);
$data = file_get_contents($cacheFile);

$tweets = json_decode($data);

$result = array();

foreach($tweets as $tweet)
$html = $tweet->text;

foreach($tweet->entities->hashtags as $hashtag)
$html = str_replace("#" . $hashtag->text, "<a href='" . $hashtag->text . "&src=hash'>#" . $hashtag->text . "</a>", $html);

foreach(array_merge((array) $tweet->entities->urls, (array) $tweet->entities->media) as $url)
$displayUrl = isset($url->expanded_url) ? $url->expanded_url : $url->url;

$html = str_replace($url->url, "<a href='" . $displayUrl . "'>" . $displayUrl . "</a>\n", $html);

foreach($tweet->entities->user_mentions as $userMention)
$html = str_replace("@" . $userMention->screen_name, "<a href='" . $userMention->screen_name . "'>@" . $userMention->screen_name . "</a>", $html);

$result[$tweet->created_at] = $html;

return $result;

This function simply takes a couple of security values provided by Twitter, the screen name of the owner of the desired timeline, and the number of tweets to retrieve. It then outputs an associative array linking the date of the Tweet with the Tweet HTML (links, usernames and hashtags are wrapped in anchor tags).

Step-by-step instructions

  1. First, go to and register your website as a new application.
  2. You'll then be taken to a screen that looks like this:

    Twitter API screen

    Don't bother trying to steal the keys you see in the image above, get your own. These ones were taken from the official Twitter documentation, anyway, so they probably don't do anything.

    Make a note of the consumer key and consumer secret values.

  3. Add the above function into your code. The first two arguments are the consumer key and consumer secret you made a note of in the last step. The third argument refers to the Twitter screen name, quite possibly your own, of the user you wish to retrieve the Tweets from (in my case, cmuirnz). The fourth argument is the number of recent tweets you wish to retrieve, I believe the maximum is 200. The final argument refers to a file that caches your recent tweets for 1 minute, so you're not making unnecessary requests to Twitter for every page a user visits.

    So, you can call it like this (but with your own keys, obviously):

    $tweets = getTweets("xvz1evFS4wEEPTGEFPHBog", "L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg", "cmuirnz", 3, "tweets.json");

    And you've got a simple of array of tweets, which you can insert into your HTML.

Lingering Questions

At this point, you may be wondering why Twitter's making us jump through hoops with authentication in order to view tweets which are publicly available. Twitter claim it's in order to better understand and manage the needs of their developers.

I, for one, believe they have a much simpler motivation. Obviously, their servers are powered by the kinetic energy of coders like you and I typing out code. The more code we have to write in order to retrieve our tweets from their servers, the less energy they need to siphon from their orbiting death-ray in order to keep their servers going.

As a staunch defender of this planet's safety from fiery sky-death, it is your duty to use the code I have provided, instead of coding it out for yourself. Think of the lives you'll save; you'll be a hero. Good luck.