How to Count Facebook Fans in PHP

Update: There’s an new easier way of retrieving the fans count using the Graph API, covered here: Counting Facebook Fans in PHP: The Graph API Way

Not too tricky this one, but very handy as the social media world is developing extremely fast. It may not be too useful to publish the fan count of your facebook fan page if you’ve got less than a hundred or so, but as soon as you jump that high, it’s a good idea to show people that they’re not the only ones following you. Same applies to Twitter and other social media platforms.

The code is fairly simple if you’re familiar with the Facebook API, and even easier if you ever used the Facebook Client for PHP library, which makes tackles this issue in (literally) three lines of code and a simple FQL query. Don’t forget that in order to work with the Facebook platform, you’ll need an API key and secret. If you haven’t got a developer account, follow this guide to set it up.

That’s probably the most difficult part of this article. Once you have a dev account and the PHP client library, all you do is:

require_once('facebook/facebook.php');
$facebook = new Facebook('api_key','api_secret');
$fql = 'select fan_count from page where page_id = your_page_id;';
$result = $facebook->api_client->fql_query($fql);
$fb_fans = $result[0]["fan_count"];

Please note! that the code above is fine for the old version of the Facebook PHP Client. They released a new one which handles things a little bit differently, so here’s the code for the new version (tested in 2.0.4):

require_once('src/facebook.php');

$facebook = new Facebook(array(
  'appId'  => 'your_app_id',
  'secret' => 'your_app_secret',
  'cookie' => true,
));

$result = $facebook->api(array(
	'method' => 'fql.query',
	'query' => 'select fan_count from page where page_id = your_page_id;'
));

$fb_fans = $result[0]['fan_count'];

Replace api_key and api_secret with your own keys and secrets, replace your_page_id with the numerical ID of the page you’d like to quote. Also, if you’re unsure what is returned, then you should run a few checks on $result using print_r or var_dump.

Well.. That’s it! I just came across this issue last week and thought somebody might find it useful. Also note that in order to optimize the load time of your page, you should cache the result for some time, perhaps a day or two. Same applies to Twitter followers count and anything else you’re doing via public APIs (unless you’re using a javascript widget of course).