Articles » Display latest Twitter tweets with PHP
Earlier this year we wrote an article showing a PHP function to display latest Twitter tweet. While that works well for displaying a single tweet we recently needed to display the latest 5 Twitter tweets on our website. The code below shows a simple way to do this.
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 28 29 30 31 32 33 34 |
< ?php
$doc = new DOMDocument();
# load the RSS document, edit this line to include your username or user id
if($doc->load('http://twitter.com/statuses/user_timeline/yourUserName.rss')) {
# specify the number of tweets to display, max is 20
$max_tweets = 5;
$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
# fetch the title from the RSS feed.
# Note: 'pubDate' and 'link' are also useful (I use them in the sidebar of this blog)
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
# the title of each tweet starts with "username: " which I want to remove
$tweet = substr($tweet, stripos($tweet, ':') + 1);
# OPTIONAL: turn URLs into links
$tweet = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $tweet);
# OPTIONAL: turn @replies into links
$tweet = preg_replace("/@([0-9a-zA-Z]+)/", "<a href=\"http://twitter.com/$1\">@$1</a>", $tweet);
echo "<li>".$tweet."</li>\n";
if ($i++ >= $max_tweets)
break;
}
echo "</ul>\n";
}
?>
|
