PHP封装的Twitter访问类实例

这篇文章主要介绍了PHP封装的Twitter访问类,通过curl调用实现针对Twitter的常用访问功能,具有一定参考借鉴价值,需要的朋友可以参考下,本文实例讲述了PHP封装的Twitter访问类,分享给大家供大家参考,具体如下:

  1. class Twitter {
  2. /**
  3. * Method to make twitter api call for the users timeline in XML
  4. *
  5. * @access private
  6. * @param $twitter_id, $num_of_tweets
  7. * @return $xml
  8. */
  9. private function api_call($twitter_id, $num_of_tweets) {
  10. $c = curl_init();
  11. curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=$num_of_tweets");
  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. $response_info = curl_getinfo($c);
  17. curl_close($c);
  18. if (intval($response_info['http_code']) == 200) {
  19. $xml = new SimpleXMLElement($response);
  20. return $xml;
  21. } else {
  22. return false;
  23. }
  24. }
  25. /**
  26. * Method to add hyperlink html tags to any urls, twitter ids or hashtags in tweet
  27. *
  28. * @access private
  29. * @param $text
  30. * @return $text
  31. */
  32. private function process_links($text) {
  33. $text = utf8_decode($text);
  34. $text = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
  35. $text = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", $text);
  36. $text = preg_replace("#(^|[\n ])\#([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://hashtags.org/search?query=\\2\" >#\\2</a>'", $text);
  37. return $text;
  38. }
  39. /**
  40. * Main method to retrieve the tweets and return html for display
  41. *
  42. * @access public
  43. * @param $twitter_id, $num_of_tweets, $timezone
  44. * @return $result
  45. */
  46. public function get_tweets($twitter_id, $num_of_tweets = 3, $timezone = "America/Denver") {
  47. $include_replies = false;
  48. date_default_timezone_set($timezone);
  49. // the html markup
  50. $cont_o = "<div tweets\">\n";
  51. $tweet_o = "<div class=\"status\">\n";
  52. $tweet_c = "</div>\n\n";
  53. $detail_o = "<div class=\"details\">\n";
  54. $detail_c = "</div>\n\n";
  55. $cont_c = "</div>\n";
  56. if ($twitter_xml = $this->api_call($twitter_id, $num_of_tweets)) {
  57. $result = $cont_o;
  58. foreach ($twitter_xml->status as $key => $status) {
  59. if ($include_replies == true | substr_count($status->text, "@") == 0 | strpos($status->text, "@") != 0) {
  60. $tweet = $this->process_links($status->text);
  61. $result .= $tweet_o . $tweet . $tweet_c . $detail_o . date('D jS M y H:i', strtotime($status->created_at)) . $detail_c;
  62. }
  63. }
  64. $result .= $cont_c;
  65. } else {
  66. $result .= $cont_o . $tweet_o . "Twitter seems to be unavailable at the moment." . $tweet_c . $cont_c;
  67. }
  68. return $result;
  69. }
  70. }

希望本文所述对大家的php程序设计有所帮助。