Quantcast
Viewing all articles
Browse latest Browse all 101

An easy way to use the Twitter API

Twitter, surely, has had one of the most successful developer outreach programmes of all time. Their relaxed attitude to data access has meant that a myriad of superb side projects has sprung up and which, in turn, fed back into the popularity of Twitter.

Universally loved by software developers, the Twitter API has set the standard for other companies when allowing open access to their database.

Recently I had reason to use the Twitter API on a personal project (a new personal portfolio actually). Since the summer of 2010 Twitter has made access to their API mandatory only if using QAuth authentication – or so I thought.

The problem with using QAuth for Twitter is one of finding the right script because you'll stumble upon that old chestnut - a PEAR module without any documentation.

After faffing around for a couple of hours I thought, “Why do I need QAuth for if all I want to do is access my personal Twitter stream and not update it on a third-party site?”

Then a more simple method hit me and all it involved was building up a query string from GET statuses/user_timeline like so: http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=andywalpole&count=20&exclude_replies=true

If you read the Twitter resource linked to above then you can add many different queries to the string including specifying whether you would like the returned resource to be JSON or XML; the number of tweets, or whether you would like to exclude replies.

From there it is just a case of using PHP's trusted Client URL Library (cURL) like so:

$ch = curl_init();

$file = fopen("textfile.json", "w+");

curl_setopt($ch, CURLOPT_URL,
    'http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=andywalpole&count=20&exclude_replies=true');

curl_setopt($ch, CURLOPT_FILE, $file);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);

fclose($file);

Now that you have your Twitter stream in a JSON file it is just a question of accessing and then looping through the content:

$twitter = file_get_contents('textfile.json');

$twitter = json_decode($twitter);

$rows = "";

foreach ($twitter as $keys => $rows) {
    
    // looped data here

    }

And that is it :)


Viewing all articles
Browse latest Browse all 101

Trending Articles