Articles » PHP function to display latest Twitter tweet

We decided to add our latest Twitter tweets to our home page as we like to micro blog. The question was how do we do it?

Twitter has various methods for data retrieval including, XML, RSS and their own API feeds that we could use. After looking at them all we decided to use the XML feed as it seemed the quickest. This is our xml feed url:

http://twitter.com/statuses/user_timeline/21885742.xml?count=5

To get yours click the RSS link on your twitter page to get your Twitter Id, your Id is the filename (without the .rss extent ion).

We then had to decide how we were going to extract the required data, as we just wanted the comment we decided to utilise cURL. Info on cURL can be found here http://php.net/manual/en/book.curl.php. If we had needed to handle more data we would probably have gone with XML_DOM.

The function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
function get_twitter_status($twitter_id, $hyperlinks, $count, $date)
{
	$c = curl_init();
	curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=$count");
	curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	$src = curl_exec($c);
	curl_close($c);
	
	$src = preg_replace("%<user>(.*?)</user>%s", "", $src);
	
	preg_match_all("%<text>(.*?)</text>%", $src, $text);
	if ($date)
		preg_match_all("%<created_at>(.*?)</created_at>%", $src, $created);
	
	foreach ($text[1] as $k => $v) {
		$status .= "<p>\"".htmlentities($v)."\"</p>";
		if ($date)
			$status .= date("D, d M Y @ H:i:s", strtotime($created[1][$k]));
	}
	
	if ($hyperlinks)
		$status = preg_replace("%([[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/])%", "<a href='$1'>$1</a>", $status);
	
	return $status;
}
?>

Its as simple as that really, to use it on a page use the following PHP code:

1
2
3
4
5
6
7
8
<?php
$twitterId = 21885742;
$hyperlinks = true; // or false to not create hyperlinks
$count = 5;
$date = true; // or false to not display the date

echo get_multiple_twitter_status($twitterId, $hyperlinks, $count, $date);
?>

Hope this helps someone!




Captcha Image