Posted By

f6design on 10/08/10


Tagged

php rss twitter tweets


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

pytheas
mfgalex
voove


Twitter RSS Feed Parser to display tweets on a website (includes caching)


 / Published in: PHP
 

URL: http://f6design.com/journal/2010/10/07/display-recent-twitter-tweets-using-php/

To use just edit the Twitter user ID which appears at the bottom of the snippet. You may want to change the location where the tweets are cached, by default they are stored at the root level of your domain. The reason for caching is that Twitter limits the number of times an RSS feed can be accessed per hour to 150.

  1. <?php
  2.  
  3. /**
  4.  * TWITTER FEED PARSER
  5.  *
  6.  * @version 1.1.4
  7.  * @author Jonathan Nicol
  8.  * @link http://f6design.com/journal/2010/10/07/display-recent-twitter-tweets-using-php/
  9.  *
  10.  * Notes:
  11.  * Caching is employed because Twitter only allows their RSS feeds to be accesssed 150
  12.  * times an hour per user client.
  13.  * --
  14.  * Dates can be displayed in Twitter style (e.g. "1 hour ago") by setting the
  15.  * $twitter_style_dates param to true.
  16.  *
  17.  * Credits:
  18.  * Hashtag/username parsing based on: http://snipplr.com/view/16221/get-twitter-tweets/
  19.  * Feed caching: http://www.addedbytes.com/articles/caching-output-in-php/
  20.  * Feed parsing: http://boagworld.com/forum/comments.php?DiscussionID=4639
  21.  */
  22.  
  23. function display_latest_tweets(
  24. $twitter_user_id,
  25. $cache_file = './twitter.txt',
  26. $tweets_to_display = 100,
  27. $ignore_replies = false,
  28. $twitter_wrap_open = '<h2>Latest tweets</h2><ul id="twitter">',
  29. $twitter_wrap_close = '</ul>',
  30. $tweet_wrap_open = '<li><span class="status">',
  31. $meta_wrap_open = '</span><span class="meta"> ',
  32. $meta_wrap_close = '</span>',
  33. $tweet_wrap_close = '</li>',
  34. $date_format = 'g:i A M jS',
  35. $twitter_style_dates = false){
  36.  
  37. // Seconds to cache feed (1 hour).
  38. $cachetime = 60*60;
  39. // Time that the cache was last filled.
  40. $cache_file_created = ((file_exists($cache_file))) ? filemtime($cache_file) : 0;
  41.  
  42. // A flag so we know if the feed was successfully parsed.
  43. $tweet_found = false;
  44.  
  45. // Show file from cache if still valid.
  46. if (time() - $cachetime < $cache_file_created) {
  47.  
  48. $tweet_found = true;
  49. // Display tweets from the cache.
  50. readfile($cache_file);
  51.  
  52. } else {
  53.  
  54. // Cache file not found, or old. Fetch the RSS feed from Twitter.
  55. $rss = file_get_contents('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name='.$twitter_user_id);
  56.  
  57. if($rss) {
  58.  
  59. // Parse the RSS feed to an XML object.
  60. $xml = simplexml_load_string($rss);
  61.  
  62. if($xml !== false) {
  63.  
  64. // Error check: Make sure there is at least one item.
  65. if (count($xml->channel->item)) {
  66.  
  67. $tweet_count = 0;
  68.  
  69. // Start output buffering.
  70.  
  71. // Open the twitter wrapping element.
  72. $twitter_html = $twitter_wrap_open;
  73.  
  74. // Iterate over tweets.
  75. foreach($xml->channel->item as $tweet) {
  76.  
  77. // Twitter feeds begin with the username, "e.g. User name: Blah"
  78. // so we need to strip that from the front of our tweet.
  79. $tweet_desc = substr($tweet->description,strpos($tweet->description,":")+2);
  80. $tweet_desc = htmlspecialchars($tweet_desc);
  81. $tweet_first_char = substr($tweet_desc,0,1);
  82.  
  83. // If we are not ignoring replies, or tweet is not a reply, process it.
  84. if ($tweet_first_char!='@' || $ignore_replies==false){
  85.  
  86. $tweet_found = true;
  87. $tweet_count++;
  88.  
  89. // Add hyperlink html tags to any urls, twitter ids or hashtags in the tweet.
  90. $tweet_desc = preg_replace('/(https?:\/\/[^\s"<>]+)/','<a href="$1">$1</a>',$tweet_desc);
  91. $tweet_desc = preg_replace('/(^|[\n\s])@([^\s"\t\n\r<:]*)/is', '$1<a href="http://twitter.com/$2">@$2</a>', $tweet_desc);
  92. $tweet_desc = preg_replace('/(^|[\n\s])#([^\s"\t\n\r<:]*)/is', '$1<a href="http://twitter.com/search?q=%23$2">#$2</a>', $tweet_desc);
  93.  
  94. // Convert Tweet display time to a UNIX timestamp. Twitter timestamps are in UTC/GMT time.
  95. $tweet_time = strtotime($tweet->pubDate);
  96. if ($twitter_style_dates){
  97. // Current UNIX timestamp.
  98. $current_time = time();
  99. $time_diff = abs($current_time - $tweet_time);
  100. switch ($time_diff)
  101. {
  102. case ($time_diff < 60):
  103. $display_time = $time_diff.' seconds ago';
  104. break;
  105. case ($time_diff >= 60 && $time_diff < 3600):
  106. $min = floor($time_diff/60);
  107. $display_time = $min.' minutes ago';
  108. break;
  109. case ($time_diff >= 3600 && $time_diff < 86400):
  110. $hour = floor($time_diff/3600);
  111. $display_time = 'about '.$hour.' hour';
  112. if ($hour > 1){ $display_time .= 's'; }
  113. $display_time .= ' ago';
  114. break;
  115. default:
  116. $display_time = date($date_format,$tweet_time);
  117. break;
  118. }
  119. } else {
  120. $display_time = date($date_format,$tweet_time);
  121. }
  122.  
  123. // Render the tweet.
  124. $twitter_html .= $tweet_wrap_open.html_entity_decode($tweet_desc).$meta_wrap_open.'<a href="http://twitter.com/'.$twitter_user_id.'">'.$display_time.'</a>'.$meta_wrap_close.$tweet_wrap_close;
  125.  
  126. }
  127.  
  128. // If we have processed enough tweets, stop.
  129. if ($tweet_count >= $tweets_to_display){
  130. break;
  131. }
  132.  
  133. }
  134.  
  135. // Close the twitter wrapping element.
  136. $twitter_html .= $twitter_wrap_close;
  137. echo $twitter_html;
  138.  
  139. // Generate a new cache file.
  140. $file = fopen($cache_file, 'w');
  141.  
  142. // Save the contents of output buffer to the file, and flush the buffer.
  143. fwrite($file, ob_get_contents());
  144. fclose($file);
  145.  
  146. }
  147. }
  148. }
  149. }
  150. // In case the RSS feed did not parse or load correctly, show a link to the Twitter account.
  151. if (!$tweet_found){
  152. echo $twitter_wrap_open.$tweet_wrap_open.'Oops, our twitter feed is unavailable right now. '.$meta_wrap_open.'<a href="http://twitter.com/'.$twitter_user_id.'">Follow us on Twitter</a>'.$meta_wrap_close.$tweet_wrap_close.$twitter_wrap_close;
  153. }
  154. }
  155.  
  156. display_latest_tweets('YOUR_TWITTER_ID');
  157.  
  158. ?>

Report this snippet  

You need to login to post a comment.