使用PHP调用Twitter的RSS

守望轩”博客右侧边栏原来有个“杂感”的栏目,用来记录短的、不能大篇幅成文的短句,或者自己比较喜欢的短句和言论。
杂感
这个栏目最开始调用微博饭否的API来做的,因为众所周知的缘故,饭否无法使用了,后来采用腾讯滔滔API来实现.2010年1月26日滔滔业务将会开始和QQ空间心情整合,只能考虑放弃。思来想去,最终还是考虑用Twitter来实现,不过Twitter在国内无法访问,不能采用js的方式来调用。本博客的服务器才国外,用php的方式访问Twitter的API应该没有问题,虽然有现成的插件“Twitter Tools”可以用,但本着尽量少用插件的目的,决定直接用php在wordpress主题里实现。twritter提供的API接口很丰富,研究一下觉得调用Twitter 比较简单,实现如下功能:

2010-04-14:发现twitter的rss访问不正常,导致获取数据失败,而原来的代码对$xml->channel->item数组没有进行正确性的判断,调整代码,加入有关判断。

1、抓取twitter RSS的内容,不需要密码,只需要用户名。
2、格式化RSS的内容,显示用户本人的推的内容及时间,排除 @replies 回复给他人的信息内容。

代码如下:

01:  <!--  my tritter  -->
02:  <?php
03:  $username='xjb';//change this to your twitter username修改为你的twitter 用户名
04:  $feedURL='http://twitter.com/statuses/user_timeline/'.$username.'.rss';
05:  $excludePattern='/'.$username.': @/'; //excludes any @replies排除@replies 内容
06:  $count=5;//  show count
07:  $i=0;
08:  
09:  if(!$xml=simplexml_load_file($feedURL)){
10:    trigger_error('Error',E_USER_ERROR);
11:  }
12:  if ( isset($xml->channel->item) || is_array($xml->channel->item) )
13:      {
14:          foreach($xml->channel->item as $item) {
15:        if ( ! preg_match("$excludePattern", $item->title)) {
16:              $filteredTitle=htmlspecialchars("$item->title");
17:              $filteredTitle=str_replace("$username: ","",$filteredTitle);
18:              //Convert the time zone in China --转成亚洲时区?
19:              date_default_timezone_set('Asia/Shanghai');
20:              $i++;
21:  
22:              if($i>$count)
23:            {
24:          break;
25:      }
26:  }
27:  ?>
28:  <li><?php echo $filteredTitle; ?>
29:  (<?php echo date("Y-m-d H:i:s",strtotime($item->pubDate)); ?>)</li>
30:  <?php } } ?>
31:  <div align="right">
32:  <a href="http://twitter.com/xjb" target="_blank">更多...</a></div>
33:  <!--  my tritter  -->

源代码下载:twitter-rss.rar



微信扫描下方的二维码阅读本文

那年今日

2008-03-06 如果生活出了错,我可以调试么? (0 个评论)

使用PHP调用Twitter的RSS》有7个想法

  1. 中国摇滚

    从blogsearch搜到了这篇文章,真的很不错,希望能看到更多的新内容,已经订阅了rssfeed,祝博主好运:)

    回复

回复 xjb 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注