Get Your Latest Tweets The Smart Way

If you’ve ever used the Twitter API to get the number of your Twitter followers, your latest status updates, or something similar using the Twitter API you may have come across a little problem that has been bugging me for a while. Twitter has a limit on the number of API requests per hour. So, If you have a high traffic blog or other website you may find that your scripts tapping into their API don’t always return with info from Twitter.

How to solve this? A solution I came up with recently involves storing the data from the Twitter API in a text file, then simply calling the file to get the data. This saves API calls and keeps you from timing out, unless of course you’re calling it somewhere else on your site.

Let’s say you want to get the number of followers you have on Twitter and display it on your WordPress blog. Copy the following code and paste it into your functions.php file.

<?php

// get and store # of Twitter followers
function get_followers($twitterid){

	//get number of Twitter followers from Twitter website
	//http://www.catswhocode.com/blog/php-snippets-to-interact-with-twitter
	$xml=file_get_contents('http://twitter.com/users/show.xml?screen_name='.$twitterid);
	if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
		$tw['count'] = $match[1];
	}
	$strfollowers = $tw['count']; //get current number of followers from Twitter

	//check the text file for last # of followers and when
	$myFile = "followers.txt";					//which text file?
	$fh = fopen($myFile, 'r') or die("error");			//open file or error msg
	$today = date("Y/m/d");						//find today's date
	$currecord = fgets($fh);					//get the first line of text file
	$arrayCurRecord = explode("::", $currecord);			//split first line into separate records
	$lastdate = $arrayCurRecord[0];					//retrieve date
	$lastfollowers = $arrayCurRecord[1];				//retrieve number of files
	fclose($fh);							//close connection to text file

	//decide wether to update text file or use current records
	if ($lastdate < $today) {
		//if text file is old we need to update it
		$stringData = $today . "::" . $strfollowers . "\n";	//next record in text file is current date + number of followers
		$fh2 = fopen($myFile, 'w') or die("error");		//open file or error msg
		fwrite($fh2, $stringData);				//write to text file
		fclose($fh2);						//close connection to text file
		return $strfollowers;
	} else {
		//if text file is from today then it's good and we use it
		return $lastfollowers;
	}

}	

?>

Then copy and paste this line into wherever you want your number of followers to show up. Don’t forget to take out my Twitter handle and put in yours instead.

<?php echo get_followers('angelagiese'); ?>

The function above stores the total of Twitter followers once per day. Whenever your first visitor sees the webpage the code is on in their browser the code finds the text file, reads the date, and if it’s a date before today it asks Twitter for the current number of followers. It then stores today’s date and the number in the text file. Each time any page calling the function is loaded after that for the current day it references the text file.

You’ll want to make sure the text file has permission to write on your server by opening your FTP client, right clicking on the file, then chosing the appropriate permissions. I’m no security expert, so you’ll have to decide for yourself whether you want to allow this solution.

Angela Giese is a web developer from the Seattle area who loves making super-useful websites with PHP, jQuery, and content management systems such as WordPress.

This is a guest post! After my cry for help a couple of weeks ago Angela very kindly offered to submit a guest post. If you would like to write a guest post for WPShout then please leave a comment below and I’ll drop you an email. It’d be absolutely wonderful to have more posts on the site to keep the content coming!


2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
rfmeier
November 24, 2010 1:07 pm

Nice. If using WordPress, wouldn’t the Transients API work well for this too?

Gilbert
November 24, 2010 11:22 am

I had the same problem and came up with a similar solution to this one. I created a PHP class called simpleCache which caches 3rd party api calls. You should check it out: https://github.com/gilbitron/PHP-SimpleCache