Create your own Twitter counter

Using Twitter API to fetch followers countTwitter follower counters are a very popular way to display the world how popular a certain website or blog has become.

The problem with these counters is that they only provides limited flexibility in look-and-feel implementation, and potentially can decrease loading times on your site.

In this post you learn to use the Twitter REST API to retrieve subscriber statistics, and use file caching to increase performance and keep things efficient.

Twitter REST API

Twitter offers a REST api that can be used for interacting with Twitter in many ways. In this specific case, we’re going to use the “users/show” API method.

The “users/show” method can be used to retrieve information about a Twitter user. In the example below are data on Tips4php:


<user>
<id>128220332</id>
<name>Tips4php</name>
<screen_name>tips4php_net</screen_name>
<location/>
−
<description>
Blog with useful information for webmasters and website owners about wordpress, php, MySQL, SEO and online marketing
</description>
−
<profile_image_url>
http://a1.twimg.com/profile_images/788337073/1270052086_ktip_normal.png
</profile_image_url>
<url>http://tips4php.net</url>
<protected>false</protected>
<followers_count>4159</followers_count>
<profile_background_color>0346AE</profile_background_color>
<profile_text_color>000000</profile_text_color>
<profile_link_color>2D2CAE</profile_link_color>
<profile_sidebar_fill_color>EDFCDE</profile_sidebar_fill_color>
<profile_sidebar_border_color>EDFCDE</profile_sidebar_border_color>
<friends_count>4255</friends_count>
<created_at>Wed Mar 31 13:35:33 +0000 2010</created_at>
<favourites_count>0</favourites_count>
<utc_offset>3600</utc_offset>
<time_zone>Copenhagen</time_zone>
−
<profile_background_image_url>
http://a3.twimg.com/profile_background_images/87846683/xe3aca610bbbe69d2b7327e93542e529.gif
</profile_background_image_url>
<profile_background_tile>true</profile_background_tile>
<profile_use_background_image>true</profile_use_background_image>
<notifications>false</notifications>
<geo_enabled>false</geo_enabled>
<verified>false</verified>
<following>false</following>
<statuses_count>68</statuses_count>
<lang>en</lang>
<contributors_enabled>false</contributors_enabled>
<follow_request_sent>false</follow_request_sent>
<listed_count>124</listed_count>
<show_all_inline_media>false</show_all_inline_media>
−
<status>
<created_at>Fri Aug 06 00:20:57 +0000 2010</created_at>
<id>20424032265</id>
−
<text>
Create heading heading specific RSS feeds in WordPress: RSS feed is a great possibility for attracting loyal reade... http://bit.ly/9KFUgi
</text>
−
<source>
<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>
</source>
<truncated>false</truncated>
<in_reply_to_status_id/>
<in_reply_to_user_id/>
<favorited>false</favorited>
<in_reply_to_screen_name/>
<geo/>
<coordinates/>
<place/>
<contributors/>
</status>
</user>

Accessing the REST API is very simple, just add the desired Twitter user name in the url below, and then you’ll get the Twitter statistics for the user returned:

http://twitter.com/users/show/<insert twitter user id here>.xml

Twitter subscriber script

Next step is to build a script that calls the Twitter REST API,  parses the feed, returns the number of subscribers and uses a cache to keep a decent performance.

<?php
$cache_age = '<insert cache age here>';
$cache_file_path = '<insert cache file path here>';
$rss_url ='<insert twitter user xml path here>';

$cache = FALSE; //Assume the cache is empty
if(file_exists($cache_file_path)) {
 $cachetime = filemtime($cache_file_path);
 $timeago = time() - $cache_age;
 if($cachetime < $timeago) {
 $cache = FALSE; //Set to false just in case as the cache needs to be renewed
 } else {
 $cache = TRUE; //The cache still ok.
 }
}

if($cache === FALSE) {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $rss_url);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $content = curl_exec($ch);
 curl_close($ch);

 if($content === FALSE) {
 echo ("Error fetching feed");
 }

 //Save data into the cache
 $fp = fopen($cache_file_path, 'w');
 fwrite($fp , $content);
 fclose($fp);
 $source = 'api';

} else {
 //Load data from the cache.
 $content = file_get_contents($cache_file_path);
 $source = 'cache';
}

$xml = new SimpleXMLElement($content);
$no_of_readers = $xml->friends_count;

echo $no_of_readers." twitter followers, $source";

?>

See example here

To make debugging easy, the example script has $cache_age=5, so data will be collected from Twitter API if the cache file is older than 5 seconds. I have also added the $source variable, that displays if the content is from the API or from the cache file.

Both things should be changed before going live with this script.

Conclusion

The script developed for this post can not only  be used for retrieving subscriber count, but can easily be modified to display some of the other  data from the “show/user” API method, or from the Twitter REST API in general.

With file caching and data as a PHP variable, the script provides very good performance and high flexibility.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

5 Replies to Create your own Twitter counter

  1. I express how much thankfulness i have when i was look thru this article. Keep on the wonderful work and i believe all your hard work will not be wasted. I will keep . Have a great day my great writer.

  2. Andrew says:

    Hi.

    Thank you in advance for your response. I’m new to using API and caching and I can’t seem to find out how to create the cache file. Do you have any resources you can show me so I can accomplish this. From what I can tell this code is exactly what I need.

    I’m getting the following errors on output:
    Warning: fopen(http://www.santasti.com/twit.txt) [function.fopen]: failed to open stream: HTTP wrapper does not support writeable connections in /home/content/… on line 32

    Warning: fwrite(): supplied argument is not a valid stream resource in /home/content/… on line 33

    Warning: fclose(): supplied argument is not a valid stream resource in /home/content/… on line 34
    701 twitter followers, api

  3. jhnidk says:

    This error message sounds like the link to your cache file isn’t correct. Typically the url has a format like this: /home/http/html/twit.txt

  4. Andrew says:

    JHNIDK,

    Thank you very much for your help. I did have the url wrong. I needed to use the local file system. All working now!

    -Andrew

  5. Jan says:

    I’m busy with this script for about 4 hours and now i going to ask for help..

    First thanks for this script, but i cannot get it to work.

    This is my setting:

    $cache_age = ‘100’;
    $cache_file_path = ‘twit.txt’;
    $rss_url =’http://twitter.com/#!/JavilDesign’;

    I get a whole list of errors.. I do not know what to do to get it working.. Can you help me with this?

    $xml = new SimpleXMLElement($content);

    Is this simpleXML for special servers? I do have a hosting that is a good one, never had trouble with php or others languages..

Comments are now closed for this article.