While Twitter returns information in several formats (such as RSS, XML), Twitter feeds are returns in RSS XML format, and I am talking about the RSS format here.
If you have looked at the Twitter API, the property
statuses/user_timeline returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user’s timeline by using the
screen_name
or
user_id
, and only be visible if they are not protected.
The resource URL must be something like this.
http:
Load the relevant page into
DOMDocument
, and will arrange as the root of the document tree.
$doc = new DOMDocument();
if($doc->load('http://twitter.com/statuses/user_timeline/[screen_name].rss')) {
}
Once you loaded the document to DOM object appropriately, you can easily traverse through the XML formatted nodes. Each node you can pick the data as in ordinary XML document, using
getElementByTagName()
.
$html .= "<ul>";
# number of elements to display. 20 is the maximum, I want to display last 5 tweets
$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
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
$pubDate = $node->getElementsByTagName('pubDate')->item(0)->nodeValue;
$link = $node->getElementsByTagName('link')->item(0)->nodeValue;
$pubDate = strtotime($pubDate);
$html .= "<li>";
$html .= "<a href="\" target="\">";
$html .= $tweet;
$html .= "</a>";
$html .= "<br /><span style="\">".date("l dS F Y G:i A e", $pubDate)."</span>";
$html .= "</li>";
if($i++ >= $max_tweets) {
break;
}
}
$html .= "</ul>";
Points of Interest
When comparing XML and RSS formats, there are some interesting differences:
- XML does not show the re-tweet in the timeline for a user, while RSS does.
- Since XML displays all the nodes, it is more descriptive than RSS returns (there is no need to spend time on manipulating).
For an example, let see how you can find number of Tweets already posted by a user.
function GetAllTweetCount($screen_name) {
$sXML = new SimpleXMLElement('http://api.twitter.com/1/users/show/'.$screen_name.'.xml', NULL, TRUE);
return number_format($sXML->statuses_count, 0, '', ',');
}