How to Use the Twitter Search API

How To Use the Twitter API

I’ve always wanted to play around with the Twitter API. Everyone seems to be doing it these days. All I needed was a reasonable excuse. So, I decided on integrating relevant Twitter posts into

Recently I created a Twitter account for the new URL shortening service. The purpose of which was to post up new release information, engage with the users and essentially put a ‘face’ onto the service. But for this to be really effective I needed followers, and the best way to get those is to start following people yourself.

Maximising RSS

The only problem was, I needed to know who to follow. This is where Twitter Search comes in. I wanted to follow anyone who was currently using the service and Twitter Search allowed me to find them.

Getting Comfy with the Twitter API

So, to make my life easier, instead of trawling through the search results by hand and manually following each user I decided to write a script to automatically follow everyone who posts a tweet that’s got a link in it.

Here’s the code:

// Parse Search Feed
$rss =& new XML_RSS("");

// Loop through all Tweets
foreach ($rss->getItems() as $item)
    // Get username of who posted it
    $user = substr($item['link'], 19 );
    $posi = strpos($user, '/');
    $user = substr($user, 0, $posi);

    // Follow the user via the Twitter API
    $req = new HTTP_Request(''.$user.'.xml');

    $req->setBasicAuth('username', 'password');
    $response = $req->sendRequest();

It's a very basic script right now, but it will form the basis of a more comprehensive solution as it matures. But, for only 10 lines of code, it's pretty powerful!

The script has 4 main parts:

  • Retrieve and parse the RSS feed for the search
  • Loop through the feed
  • Extract the username from the link of each tweet
  • Use the Twitter API to follow the creator of the tweet

Obviously there are some issue with duplicates to be ironed out, and I think I'd like to store some of this information in a database too, but that can all come later. For now, I can say that I've dipped my toe into the world of the Twitter API and so far I like what I've seen.


To use this script, you'll need to install and configure PEAR. I used the XML_RSS and HTTP_Request packages in this example.

Sorry, comments for this entry are closed at this time.