php读取twitter feed
<?php class Twitter{ protected $twitURL = 'http://api.twitter.com/1/'; protected $xml; protected $tweets = array(), $twitterArr = array(); protected $pversion = "1.0.0"; public function pversion(){ return $this->pversion; } public function loadTimeline($user, $max = 20){ $this->twitURL .= 'statuses/user_timeline.xml?screen_name='.$user.'&count='.$max; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->twitURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $this->xml = curl_exec($ch); return $this; } public function getTweets(){ $this->twitterArr = $this->getTimelineArray(); $tweets = array(); foreach($this->twitterArr->status as $status){ $tweets[$status->created_at->__toString()] = $status->text->__toString(); } return $tweets; } public function getTimelineArray(){ return simplexml_load_string($this->xml); } public function formatTweet($tweet){ $tweet = preg_replace("/(http(.+?))( |$)/","<a href=\"$0\">$1</a>$3", $tweet); $tweet = preg_replace("/#(.+?)(\h|\W|$)/", "<a href=\"https://twitter.com/i/#!/search/?q=%23$1&src=hash\">#$1</a>$2", $tweet); $tweet = preg_replace("/@(.+?)(\h|\W|$)/", "<a href=\"http://twitter.com/#!/$1\">@$1</a>$2", $tweet); return $tweet; } }
调用方法
<?php $twitter = new Twitter(); $feed = $twitter->loadTimeline("phpsnips")->getTweets(); foreach($feed as $time => $message){ echo "<div class='tweet'>".$twitter->formatTweet($message)."<br />At: ".$time."</div>"; }