1

Twitter API using TwitterOAuth (PHP Library)

twitter-logo-blue

I was recently working on a project that needed Twitter API integration to bring followers data to a web application dynamically using Twitter API call.

This can be a challenging task because it requires many things, and there is not lot of sample code provided by Twitter for this matter.

In this pursuit, I came across TwitterAuth, an open source free library for accessing Twitter API. Here is link to it and description from original developer Abraham Williams.

The most popular PHP library for use with the Twitter OAuth REST API. https://twitteroauth.com
Sample Code:

require "autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

define('CONSUMER_KEY', 'YOUR_VALUE');
define('CONSUMER_SECRET', 'YOUR_VALUE');
define('ACCESS_TOKEN', 'YOUR_VALUE');
define('ACCESS_TOKEN_SECRET', 'YOUR_VALUE');

function search(array $query)
{
$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
return $toa->get('followers/list', $query);
}

$output = "";

if(isset($_REQUEST["screen_name"]))
{ 
$query = array(
"screen_name" => $_REQUEST["screen_name"],
"count" => 20
);
$results = search($query);

foreach ($results->users as $user) {
$output .= $user->screen_name . "\t" . $user->followers_count . "\n";
}
}
echo "letter\tfrequency\n";
echo $output;

Additional requirements:
You do need to register your Twitter App from Twitter developer website here: https://apps.twitter.com/
Another tutorial about it can be found here by The Practice of Programming blog.
I hope you found it helpful.

 

humayun

  • There are also more PHP Twitter API clients available, but for this one I was able to get started quickly so I am mentioning that.