Steveiscreative
10/18/2012 - 8:52 PM

PHP function to grab Twitter feed (JSON).

PHP function to grab Twitter feed (JSON).

<?php

/**
 * TweetFeed, Get listing of twitter feed. 
 * By default an <ul> is used but customized to your own liking. 
 * @param  STRING $screenname, Twitter screenname
 * @param  INT $count, Number of tweets to display
 */

function tweetFeed( $screenname, $count )
{
	date_default_timezone_set('America/New_York');
	$jsonTwitURL = "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$screenname;
	$JSON = file_get_contents($jsonTwitURL); 
	$tweets = json_decode($JSON, true);

	echo '<ul>';
	
	for( $i = 0; $i < $count; $i++)
	{ 
		/**
		 * Get json objects & GO CRAZY!
		 */
		$tweet_text = $tweets[$i]['text'];
		// Linkify 
		$tweet_text = str_pad($tweet_text, 3, ' ', STR_PAD_LEFT);
	        $tweet_text = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "<a href=\"\\0\">\\0</a>", $tweet_text);
	        $tweet_text = preg_replace("(@([a-zA-Z0-9\_]+))", "<a href=\"http://www.twitter.com/\\1\">\\0</a>", $text);
	        $tweet_text = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', $tweet_text);
		$tweet_date = $tweets[$i]['created_at'];
		$datePosted = date( 'n/d', strtotime($tweet_date));
		echo '<li>'.$tweet_text.' '. $datePosted.'</li>';
	}

	echo '</ul>';
}

?>