Sunday, March 31, 2013

Twitter API 1.1 Tutorial

Twitter has launched a new API version 1.1 so you need to update your PHP scripts. If you use Abraham Williams - @abraham twitteroauth.php script you need to update it like this: find row public $host = "https://api.twitter.com/1/"; and replace with public $host = "https://api.twitter.com/1.1/";. Download the script at http://github.com/abraham/twitteroauth.

If you don't update your code like this some functions will not work, like Twitter search. You need to register your application at http://dev.twitter.com/apps/new. Once you register your application get following keys:Consumer key, Consumer secret, Access token secret, Access token and put them in your code. You must make sure that your host supports cURL.

OK here is the directory structure:
index.php
twitteroauth
- OAuth.php
- twitteroauth.php
and here is index.php:
<?php
$consumer_key = "";
$consumer_secret = "";
$access_key = "";
$access_secret = "";

require_once('twitteroauth/twitteroauth.php');

// create an object from TwitterOAuth
$connection = new TwitterOAuth ($consumer_key ,$consumer_secret , $access_key , $access_secret );

$content = $connection->get("statuses/user_timeline",
                             array('screen_name'=>'ibm',
                                   'count'=>'20') );

foreach( $content as $item )
{
  echo $item->text."<br/><br/>\n";
}
?>
Yellow highlighted is the method name and green highlighted text are parameters
for the API call. This
script shows last 20 tweets from IBM. Full info is at statuses/user_timeline
API page.
<?php
$consumer_key = "";
$consumer_secret = "";
$access_key = "";
$access_secret = "";

require_once('twitteroauth/twitteroauth.php');

// create an object from TwitterOAuth
$connection = new TwitterOAuth ($consumer_key ,$consumer_secret , $access_key , $access_secret );

$content = $connection->get("search/tweets",
                             array('q'=>'bar',
                                   'geocode'=>'37.781157,-122.398720,100km',
                                   'count'=>'5',
                                   'lang'=>'en'));

echo"<pre style='border:dotted;padding:5px;background:lightgrey'>";
var_dump($content->statuses[0]->text);
var_dump($content->statuses[0]->user->id);
var_dump($content->statuses[0]->user->screen_name);
echo"</pre>";

echo"<pre style='border:dotted;padding:5px;background:lightgrey'>";
print_r($content);
echo"</pre>";
?>
This code shows first tweet, user_id and screen name. print_r($content) shows first five results for keyword 'bar' 100 km around San Francisco (37.781157,-122.398720) in English. Complete reference is at search/tweets API page.