How to get number of twitter followers for any account (including yours) with PHP

I needed a few days ago a way to get my twitter followers’ count for an app and I did a small research on StackOverflow. One of the advices was to use another service for that, because the twitter API doesn’t support that anymore.

Yeah, but it does :) Here’s how to get it:

  1. Register your app from here
  2. Pull TwitterAPIExchange.php from here.
  3. Then write this piece of code and s/YOUR DATA HERE with the corresponding field from the point one. (see above)
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
    'oauth_access_token' => "YOUR DATA HERE",
    'oauth_access_token_secret' => "YOUR DATA HERE",
    'consumer_key' => "YOUR DATA HERE",
    'consumer_secret' => "YOUR DATA HERE"
);

$url = 'https://api.twitter.com/1.1/users/show.json';
$getfield = '?screen_name=bogomep';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$output =  $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();
	
	
$rs = json_decode($output, true);
echo $rs['followers_count'];
?>

 

Adding more? In order to fight with  twitter API limitations you can “cache” your variable and refresh it every 15 min:

<?php
require_once('TwitterAPIExchange.php');
$settings = array(
    'oauth_access_token' => "YOUR DATA HERE",
    'oauth_access_token_secret' => "YOUR DATA HERE",
    'consumer_key' => "YOUR DATA HERE",
    'consumer_secret' => "YOUR DATA HERE"
);

$url = 'https://api.twitter.com/1.1/users/show.json';
$getfield = '?screen_name=bogomep';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$output =  $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();
	
	
$rs = json_decode($output, true);
$f_count = $rs['followers_count'];
apc_add ('total_count', $f_count, 900);
echo apc_fetch('total_count');
?>

Enjoy and follow me on twitter @bogomep:)