Example Twitter Follower Counter

Custom Twitter Badge

An example of what can be accomplished by creating your own Twitter Badge.

So you're on Twitter now? Like back in high school, we all want to be popular on Twitter as well. Prove it by displaying your followers count with this simple PHP script.

One thing that annoys me with all third party web services is they feel the need to brand their widgets. I don't blame them for doing this but it deters me from ever using them. What usually results from this is I tinker around and figure out a way to get the data I need without all their ugly branding.

The Setup

First we'll need to use PHP's built-in curl function. This will grab the output of other web pages, files, etc. Note I lifted the script below from another website so feel free to correct me on it.

function curl($url) { $ch = curl_init($url); curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_HEADER, 0); curl_setopt($ch,CURLOPT_USERAGENT,"www.YOURDOMAIN.com"); curl_setopt($ch,CURLOPT_TIMEOUT,10); $data = curl_exec($ch); curl_close($ch); return $data; }

Custom Twitter Badge Function

Next, we create the function that parses the curl output. This uses the Twitter API. Simply call the function with your own Twitter username and it will return the number of followers you have:

function GetTwitterFollowerCount($username) { $twitter_followers = curl("http://twitter.com/statuses/user_timeline/".$username.".xml?count=1"); $xml = new SimpleXmlElement($twitter_followers, LIBXML_NOCDATA); return $xml->status->user->followers_count; } echo GetTwitterFollowerCount("YourTwitterName");

Notes

Please take into consideration that you can only ping Twitter 150 times per hour. Because of this, it would be wise to create a text file and use it to cache your followers count. Also the function will only return a plain ol' number. Its up to your to think of a creative way to display this to your site's visitors. The more attractive you make it, the more likely your users will click it.

Related Posts: