如果你有一个属于自己的博客(不是在新浪或者网易上免费申请的那种),都会想把自己的各种信息都展示在首页上。比如你的相册,你好友的链接,你的微博信息,当然还有你的Twitter信息。
由于不可说的原因,Twitter被墙了。虽然不能直接访问了,但是哪里有什么就,哪里就有什么,魔高一尺道高一丈。这里介绍一个简单的用PHP获取你的Twitter信息方法,当然前提是你的服务器在墙外,你的博客是基于PHP的。
PHP Class For Twitter
class Twitter {
public $tweets = array();
public function __construct($user, $limit = 5) {
$user = str_replace(‘ OR ‘, ‘%20OR%20’, $user);
$feed = curl_init(‘http://search.twitter.com/search.atom?q=from:'. $user .‘&rpp=’. $limit);
curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
curl_setopt($feed, CURLOPT_HEADER, 0);
$xml = curl_exec($feed);
curl_close($feed);
$result = new SimpleXMLElement($xml);
foreach($result->entry as $entry) {
$tweet = new stdClass();
$tweet->id = (string) $entry->id;
$user = explode(‘ ‘, $entry->author->name);
$tweet->user = (string) $user[0];
$tweet->author = (string) substr($entry->author->name, strlen($user[0])+2, -1);
$tweet->title = (string) $entry->title;
$tweet->content = (string) $entry->content;
$tweet->updated = (int) strtotime($entry->updated);
$tweet->permalink = (string) $entry->link[0]->attributes()->href;
$tweet->avatar = (string) $entry->link[1]->attributes()->href;
array_push($this->tweets, $tweet);
}
unset($feed, $xml, $result, $tweet);
}
public function getTweets() { return $this->tweets; }
}
public $tweets = array();
public function __construct($user, $limit = 5) {
$user = str_replace(‘ OR ‘, ‘%20OR%20’, $user);
$feed = curl_init(‘http://search.twitter.com/search.atom?q=from:'. $user .‘&rpp=’. $limit);
curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
curl_setopt($feed, CURLOPT_HEADER, 0);
$xml = curl_exec($feed);
curl_close($feed);
$result = new SimpleXMLElement($xml);
foreach($result->entry as $entry) {
$tweet = new stdClass();
$tweet->id = (string) $entry->id;
$user = explode(‘ ‘, $entry->author->name);
$tweet->user = (string) $user[0];
$tweet->author = (string) substr($entry->author->name, strlen($user[0])+2, -1);
$tweet->title = (string) $entry->title;
$tweet->content = (string) $entry->content;
$tweet->updated = (int) strtotime($entry->updated);
$tweet->permalink = (string) $entry->link[0]->attributes()->href;
$tweet->avatar = (string) $entry->link[1]->attributes()->href;
array_push($this->tweets, $tweet);
}
unset($feed, $xml, $result, $tweet);
}
public function getTweets() { return $this->tweets; }
}
如何使用:
echo ‘<ul>’;
foreach ($tweets as $tweet) {
echo ‘<li>’. $tweet->content .‘ by <a href=”http://twitter.com/'. $tweet->user .‘“>’. $tweet->author .‘</a></li>’;
}
echo ‘</ul>’;
foreach ($tweets as $tweet) {
echo ‘<li>’. $tweet->content .‘ by <a href=”http://twitter.com/'. $tweet->user .‘“>’. $tweet->author .‘</a></li>’;
}
echo ‘</ul>’;
‘jun1st’是你的Twitter用户名,5是此次获取的tweet的数目。传入的user可以是多个的,用’OR’链接,比如’jun1st OR jun2nd’
从类中可以看到,你可以从$tweet中获取id,发布时间,Avatar等数据