65.9K
CodeProject is changing. Read more.
Home

Read Tweets with PHP

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 4, 2011

CPOL
viewsIcon

16322

Tweets are one of the mostly used for status sharing these days. This tip highlights one of the easiest ways to display Tweets in PHP.

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://twitter.com/statuses/user_timeline/[screen_name].[format]
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')) {
    // The retrieving logic goes here
}
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 .= "
    "; # 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; // Here you can do various formatting to your results. Have a look at the following two lines. // OPTIONAL: the title of each tweet starts with "username: " which I want to keep //$tweet = substr($tweet, stripos($tweet, ':') + 1); // DateTime conversion $pubDate = strtotime($pubDate); $html .= "
  • "; $html .= ""; $html .= $tweet; $html .= ""; $html .= "
    ".date("l dS F Y G:i A e", $pubDate).""; $html .= "
  • "; if($i++ >= $max_tweets) { break; } } $html .= "
";
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, '', ',');
}