Get Twitter Tweets


/ Published in: PHP
Save to your folder(s)

Some PHP code that can be used to get formatted HTML containing N number of tweets for a given twitter user.


Copy this code and paste it in your HTML
  1. <?php
  2. /*
  3. Description: Twitter PHP code
  4. Author: Andrew MacBean
  5. Version: 1.0.0
  6. */
  7.  
  8. /** Method to make twitter api call for the users timeline in XML */
  9. function twitter_status($twitter_id) {
  10. $c = curl_init();
  11. curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml");
  12. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  13. curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3);
  14. curl_setopt($c, CURLOPT_TIMEOUT, 5);
  15. $response = curl_exec($c);
  16. $responseInfo = curl_getinfo($c);
  17. if (intval($responseInfo['http_code']) == 200) {
  18. if (class_exists('SimpleXMLElement')) {
  19. $xml = new SimpleXMLElement($response);
  20. return $xml;
  21. } else {
  22. return $response;
  23. }
  24. } else {
  25. return false;
  26. }
  27. }
  28.  
  29. /** Method to add hyperlink html tags to any urls, twitter ids or hashtags in the tweet */
  30. function processLinks($text) {
  31. $text = utf8_decode( $text );
  32. $text = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text );
  33. $text = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", $text);
  34. $text = preg_replace("#(^|[\n ])\#([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://hashtags.org/search?query=\\2\" >#\\2</a>'", $text);
  35. return $text;
  36. }
  37.  
  38. /** Main method to retrieve the tweets and return html for display */
  39. function get_tweets($twitter_id,
  40. $nooftweets=3,
  41. $dateFormat="D jS M y H:i",
  42. $includeReplies=false, $dateTimeZone="Europe/London",
  43. $beforeTweetsHtml="<ul>",
  44. $tweetStartHtml="<li class=\"tweet\"><span class=\"tweet-status\">",
  45. $tweetMiddleHtml="</span><br/><span class=\"tweet-details\">",
  46. $tweetEndHtml="</span></li>",
  47. $afterTweetsHtml="</ul>") {
  48.  
  49. date_default_timezone_set($dateTimeZone);
  50. if ( $twitter_xml = twitter_status($twitter_id) ) {
  51. $result = $beforeTweetsHtml;
  52. foreach ($twitter_xml->status as $key => $status) {
  53. if ($includeReplies == true | substr_count($status->text,"@") == 0 | strpos($status->text,"@") != 0) {
  54. $message = processLinks($status->text);
  55. $result.=$tweetStartHtml.$message.$tweetMiddleHtml.date($dateFormat,strtotime($status->created_at)).$tweetEndHtml;
  56. ++$i;
  57. if ($i == $nooftweets) break;
  58. }
  59. }
  60. $result.=$afterTweetsHtml;
  61. }
  62. else {
  63. $result.= $beforeTweetsHtml."<li id='tweet'>Twitter seems to be unavailable at the moment</li>".$afterTweetsHtml;
  64. }
  65. echo $result;
  66. }
  67. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.