« Back to all articles

Getting a twitter user's latest posts using API v1.1 and Guzzle (PHP)

07 July 2013

I’ll keep this brief. Install Guzzle however you wish, but I recommend using composer:

{% highlight javascript %}

    {
        "require": {
            "guzzle/guzzle": "~3.1.1"
        }
    }

{% endhighlight %}

Then use the following code:

{% highlight php startinline %}

    $twitter_client = new \Guzzle\Http\Client('https://api.twitter.com/{version}', array(
        'version' => '1.1'
    ));
    $twitter_client->addSubscriber(new \Guzzle\Plugin\Oauth\OauthPlugin(array(
        'consumer_key'  => TWITTER_CONSUMER_KEY,
        'consumer_secret' => TWITTER_CONSUMER_SECRET,
        'token'       => TWITTER_ACCESS_TOKEN,
        'token_secret'  => TWITTER_ACCESS_TOKEN_SECRET
    )));

    $request = $twitter_client->get('statuses/user_timeline.json');
    $request->getQuery()->set('count', 5);
    $request->getQuery()->set('screen_name', 'YOURUSERNAME');
    $response = $request->send();

    $tweets = json_decode($response->getBody());

{% endhighlight %}

Don’t forget to put your constants somewhere.