Here’s an easy way to display the number of Twitter followers you (or another user) have in PHP using the Twitter REST API.
This was based off NealGrosskopf.com but was revised to use the Twitter API and not require a logged-in session.
First, declare the necessary functions:
<?php function curl($url) { $ch = curl_init($url); curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_HEADER, 0); curl_setopt($ch,CURLOPT_USERAGENT,"__YOUR_DOMAIN__"); curl_setopt($ch,CURLOPT_TIMEOUT,10); $data = curl_exec($ch); curl_close($ch); return $data; } function GetTwitterFollowerCount($username) { $twitter_followers = curl("http://api.twitter.com/1/statuses/user_timeline.xml?count=2&amp;screen_name=".$username); $xml = new SimpleXmlElement($twitter_followers, LIBXML_NOCDATA); return $xml->status->user->followers_count; } ?>
Now, a simple function displays the count:
<?php echo GetTwitterFollowerCount("__USER_NAME__"); ?>
Replace __YOUR_DOMAIN__
with the domain of the page making the API call, and __USER_NAME__
with the name of the user you want the information on.
Works for me.
UPDATE: For some reason, count=1
broke, but it works with count=2
. Either change to count=2
(to reduce the download size) or omit the count=
parameter completely (but it can inflate the download size if you have a lot of followers.)
UPDATE 2: If you are using this to fire on every page load, make sure you don’t exceed the Twitter API Rate Limit. If you think you may, you might want to cache the results, else risk being blocked by the Twitter API.