Posts tagged ‘PHP’

April 28th, 2010

Simple PHP Twitter script

UPDATE: The new Twitter API v1.1 no longer supports this code. You will need to authenticate before using it. Here is a little tutorial on how to do that http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/

I broke out this useful little PHP Twitter script from the WordPress theme jessica-fletcher-redux, which happens to be the theme I used as a template for this blog. There were a few issues I needed to overcome in order to make this work. I’m hosting this WordPress blog on Windows Server running IIS7. By default many PHP functions are disabled for security so you have to implement a work around.

The get_url_contents($url) function was added to overcome a security problem on IIS where file_get_contents() is not allowed. The other issues to is to make sure you grant write permission to PHP so it can write to your twittercache.xml file. These two changes make for a very clean twitter readout that can easily be styled using CSS.

<?php

function get_url_contents($url){
        $crl = curl_init();
        $timeout = 5;
        curl_setopt ($crl, CURLOPT_URL,$url);
        curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $ret = curl_exec($crl);
        curl_close($crl);
        return $ret;
}

function generatetwitter($twittername){

	$username = $twittername; // Your twitter username.
	if ($username == ""){
		$username = "discorax";
	}
	$limit = "15"; // Number of tweets to pull in.
	/* These prefixes and suffixes will display before and after the entire block of tweets. */
	$prefix = ""; // Prefix - some text you want displayed before all your tweets.
	$suffix = ""; // Suffix - some text you want displayed after all your tweets.
	$tweetprefix = "<li>"; // Tweet Prefix - some text you want displayed before each tweet.
	$tweetsuffix = "</li> \r"; // Tweet Suffix - some text you want displayed after each tweet.
	$feed_string = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $limit;  

 function parse_feed($feed, $prefix, $tweetprefix, $tweetsuffix, $suffix, $username) {
		$feed = str_replace("<", "<", $feed);   		$feed = str_replace(">", ">", $feed);
		$clean = explode("<content type=\"html\">", $feed);
		$link = explode("search.twitter.com,2005:", $feed);
		$amount = count($clean) - 1;
		echo $prefix;
			for ($i = 1; $i <= $amount; $i++) {   				$cleaner = explode("</content>", $clean[$i]);
				$linker = explode("</id>", $link[$i+1]);
				$this_tweets = str_replace("&apos;", "'", $cleaner[0]);
				$this_tweets = str_replace("&gt;", ">", $this_tweets);
				$this_tweets = preg_replace('!<a href.*?>!', '', $this_tweets);
				$this_tweets = preg_replace('!</a>!', '', $this_tweets);
				echo $tweetprefix.'<a href="http://twitter.com/'.$username.'/status/';
				echo $linker[0];
				echo '" target="_blank">'.$this_tweets.'</a>';
				echo $tweetsuffix;
			}
		echo $suffix;
	}

	$twitter_cache_file = 'twittercache.xml';

	$mtime= null;

	if($mtime== null ||(time()-$mtime)>(9*60)){// 9 minutes or older?
		$content=get_url_contents($feed_string);
		if(strlen($content)>0){
			$cache_static=fopen($twitter_cache_file,'w+');
			fwrite($cache_static,$content);
			fclose($cache_static);
		}
	}else{
		$mtime=filemtime($twitter_cache_file);
		}

	if (!@file_get_contents($twitter_cache_file)){
		  echo __('Oops, something went wrong. Did you rename the cache folder? The cache file? You shouldn\'t have done that...', 'jfr_theme');
	}else {
		  $twitterFeed = file_get_contents($twitter_cache_file);
	}

	parse_feed($twitterFeed, $prefix, $tweetprefix, $tweetsuffix, $suffix, $username);  

}
?>

Setup is easy. You simply need to call the generatetwitter() function like so.

<php
echo "<div>";
echo "<ul>";
generatetwitter("discorax");
echo "</ul></div>";
?>

When you’re uploading the files to your server make sure to include a blank twittercache.xml file in the same directory as the script. You can change this location by changing the value of the $twitter_cache_file variable (line 48 above) to a path where you keep the twittercache.xml file (make sure you grant write permission to that folder).

That’s it. It’s a clean little code snippit for pulling a user’s twitter feed which you can easily extend using a simple form to select your twitter account. Happy coding.