PHP: Twitter feed tutorial

In this tutorial I will explain you in details how to parse and format a Twitter RSS feed with your latest tweets. What we need to know is the basic structure of a Twitter feed, its URL and how to convert into HTML links all the plain text URLS contained within the feed. First of all, the basic structure of a Twitter feed URL is followed by your Twitter ID and ended with .rss. To get your Twitter ID, simply visit this site and enter your Twitter username into the form. Done that, you're ready to work with a Twitter feed.

Structure of a Twitter feed

A Twitter feed is simply an XML file where all your tweets are contained within item elements:


Here's a brief description of each element:

title, description
Actual content of your tweets.
A date in the format Sun, 29 May 2011 02:33:47 +0000 showing when your tweets have been published.
guid, link
The link to your tweets.
An HTML link pointing to the web site or web service you're using to post your tweets.
Your GeoLocation data (if any).

Converting plain text URLs into HTML links

Converting plain text URLs into HTML links requires the use of structured regular expression patterns to match and replace such URLs with HTML links. Fortunately, the UrlLinker PHP utility does this job for us, so we're going to use it in our example.

Parsing and displaying the feed

We'll use SimpleXML to parse and display our Twitter feed:


    $feed = file_get_contents('');

    $tweets = simplexml_load_string($feed);
    foreach($tweets->channel->item as $tweet) {
        $raw_title = $tweet->title;
        $title = htmlEscapeAndLinkUrls($raw_title);
        $title = str_replace('gabromanato:', '', $title);
        $raw_date = $tweet->pubDate;
        $date = strftime('%d-%m-%Y %H:%M:%S', strtotime($raw_date));
        echo '<li>' . $title . "\n" . 
        '<div class="pubdate">' . $date . 
        '</div>' . "\n" . "</li>\n";


As you can see, we've used the UrlLinker utility to convert our plain text URLs into HTML links. We've also used the strftime() function to properly format the date returned by each tweet. You can see the demo below.


Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.