Blog » Fetching tweets using Twitter oAuth API easily with PHP

Fetching tweets using Twitter oAuth API easily with PHP

Ever since Twitter removed RSS support from their API it's no longer possible to parse an RSS feed for a public Twitter account to get tweets from a user's timeline. You now have to go through Twitter's oAuth API, which can be a bit of a pain, but it's not that hard if you use existing HTTP clients for PHP, like Guzzle.

We also don't have to write much code, and that's something I personally like. ;-)

First of all, install Guzzle into your project using Composer.

Once installed, include the autoload for Composer if you haven't done so already:

require_once 'vendor/autoload.php';

Now, we initialise the Guzzle client and set the oAuth auth tokens:

$client = new \Guzzle\Http\Client('{version}', array(
'version' => '1.1'

$client->addSubscriber(new \Guzzle\Plugin\Oauth\OauthPlugin(array(
'consumer_key' => 'insert_consumer_key_here',
'consumer_secret' => 'insert_consumer_secret_here',
'token' => 'insert_token_here',
'token_secret' => 'insert_token_secret_here'

consumer_keyconsumer_secrettoken and token_secret values can be found once you've added an application after signing in to Twitter's developer site. After adding your application, make sure to hit the "Create my access token" button at the bottom of the app page to generate the token and token_secret values!

All that's left to do now is call statuses/user_timeline.json with the appropriate screen name to pull down the tweets in JSON format. We'll decode that JSON into a PHP array to make it easy to loop over.

$response = $client->get('statuses/user_timeline.json', array(), array(
'query' => array(screen_name' => 'insert_username_of_user_to_get_tweets_from')

$tweets = json_decode($response);

foreach($tweets as $tweet) {
echo $tweet->text;
echo $tweet->created_at;

screen_name refers to the username of the account you want the tweets from.

Other things I've left off here are caching, limiting the number of tweets, and probably a few more things. I'll leave those to the reader. :-)

More examples of using the Twitter API can be found on the Twitter developer documentation site.