Display recent Twitter tweets using PHP

Here is a code to display recent twitter tweets using 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/username.rss')) {

        # specify the number of tweets to display, max is 20
        $max_tweets = 20;

        $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>";

                if ($i++ >= $max_tweets)
                        break;
        }
}
Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*