How to: Create a Twitter feed with full syntax support

Written by: Phil Sturgeon

Hello, I am Phil and I have been developing websites since 1999. I started my career freelancing then ran a small web development team for over a year. Now I work as a developer for HargreavesLansdown and use my spare time to develop, write articles about programming and create slightly intoxicated screencasts. For more of my antics follow me on twitter @PhilSturgeon.

If you have a project that you would like to add a Twitter feed to, but do not want to add in a massive library for the one feed, try this little snippet of procedural code that I recently implemented on pyrocms.com.

Expressions

Detect URL’s

 '|([a-z]{3,9}://[a-z0-9-_./?&+]*)|i' => '<a href="$0" target="_blank">$0</a>', 

Detect E-mail addresses

 '|[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,6}|i' => '<a href="mailto:$0">$0</a>', 

Detect @usernames’s

 '|@([a-z0-9-_]+)|i' => '<a href="http://twitter.com/$1" target="_blank">$0</a>', 

Detect #tags

 '|#([a-z0-9-_]+)|i' => '<a href="http://twitter.com/search?q=#$1" target="_blank">$0</a>' 

Example

Lets put this together to create a very simple working example.

<?php
// Fetch the Tweets in JSON form and convert to a PHP object
$tweets = json_decode(file_get_contents('http://twitter.com/statuses/user_timeline/philsturgeon.json?count=10'));
// List all regular expression rules
$patterns = array(
			'|([a-z]{3,9}://[a-z0-9-_./?&+]*)|i'		=> '$0', // Detect URL's
			'|[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,6}|i'	=> '$0', // Detect Email Addresses

			'|@([a-z0-9-_]+)|i'	=> '$0', 			// Detect Twitter @usernames
			'|#([a-z0-9-_]+)|i'	=> '$0'	// Detect Twitter #tags
			);

// Loop through tweets
foreach($tweets as $tweet)
{
	// Run all rules to replace syntax with HTML
	$tweet->text = preg_replace(array_keys($patterns), array_values($replace), $tweet->text); 

	// Display the tweet with syntax enabled
	echo '

'.date('d/m/Y', strtotime($tweet->created_at)) . ' ' . $tweet->text.'

';
}
?>

This is not following perfect coding practices, it will not cache data and might not be the most optimal implementation but I was trying to keep the amount of code low to show the simplicity of how it can be achieved.

Instead of showing a users timeline you can use the same code to show search results with the url:

http://search.twitter.com/search.json?q=pyrocms

Now, go forth and tweet!

Tags: , , , , ,

Be the first to comment.

Tell us what you think !

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>