Enterprise Integration Zone is brought to you in partnership with:

Lorna Jane Mitchell is a PHP developer, blogger, trainer and evangelist from Leeds in the UK. She is active with phpwomen.org and her local user group PHP North West, and writes for a variety of outlets, including her own blog at lornajane.net. She is an active member of the PHP and open source communities and contributes to the joind.in event feedback project. When she's not at her computer, Lorna enjoys yarn craft, hobby electronics, and her home renovation project. Lorna is a DZone MVB and is not an employee of DZone and has posted 78 posts at DZone. You can read more from them at their website. View Full User Profile

Twitter Search API Using PHP and Guzzle

07.12.2013
| 4385 views |
  • submit to reddit

In case you missed it, Twitter updated their APIs recently, so that you have to authenticate to use even their search APIs to return publicly-available results. This is an increasing trend for API providers, to provide either very limited or nonexistent access for unauthenticated users, I think so they can rate limit consumers that swamp them. To cut a long story short, that meant I needed to update my dashboards that keep an eye on twitter searches to do more than just call file_get_contents in the general direction of the right URL.

I picked Guzzle to achieve this, mostly out of curiosity. I tend to favour extensions over userland code because they perform better, but I had it on good authority that Guzzle actually understands HTTP correctly (surprisingly unusual in PHP implementations of "HTTP" or "REST" tools!), and for a low-traffic personal dashboard, performance isn't an issue. Guzzle is a modern library with Composer support and a tidy, modern interface, and I enjoyed using it, so I thought I'd share how my twitter search consuming code looks.

Searching Twitter with Guzzle

These examples contain references to a variable called $twitter - this contains twitter-related settings and lives in a separate config file to make it harder for me to share my API keys inappropriately :)

First, we create the Guzzle client to talk to twitter. This has a lovely trick for using URL templates and replacing bits of that with variables, so I've used it when I first connect. Twitter's API is currently at v1.1, but this may change, so my code looks like this:

$twitter_client = new \Guzzle\Http\Client('https://api.twitter.com/{version}', array(
        'version' => '1.1'
    ));

Next, we need to attach our authentication details to the request. Twitter uses OAuth which is very convenient, and Guzzle supports this, so we just need to add our details to the client we created, which looks like this:

$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']
)));

The settings for your twitter security credentials can be obtained by registering for an API key at http://dev.twitter.com/apps. You can then generate an access token and secret from the same page, which is very handy, and use them here.

At this point, we can make any twitter API calls we'd like to; this example goes on to make search queries, but there's a raft of documentation for anything else you might like to do with twitter and Guzzle.

The search terms themselves can contain AND and OR operators, and you can also pass a selection of other parameters to customise the results for language, recentness, and who knows what else - again, excellent documentation is available. This example is just a basic search, which I achieve with the following:

$request = $twitter_client->get('search/tweets.json');
$request->getQuery()->set('q', $search);
$response = $request->send();

Twitter speaks JSON, so we will want to json_decode() the body of the response:

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

This gives an array of tweets, and you can inspect the fields to find what you need, I mostly use the following:

  • text: the body of the tweet
  • id_str: the identifier of the tweet
  • user['screen_name']: the user whose tweet this is

Hopefully that gives you an easy example to start using Guzzle for this, and many other, applications.




Published at DZone with permission of Lorna Mitchell, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)