PHP调用Twitter的RSS的实现代码

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

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

代码如下:
复制代码 代码如下:

<!-- my tritter -->
<?php
$username='xjb';//change this to your twitter username修改为你的twitter 用户名
$feedURL='http://twitter.com/statuses/user_timeline/'.$username.'.rss';
$excludePattern='/'.$username.': @/'; //excludes any @replies排除@replies 内容
$count=5;// show count
$i=0;

if(!$xml=simplexml_load_file($feedURL)){
trigger_error('Error',E_USER_ERROR);
}
foreach($xml->channel->item as $item) {
if ( ! preg_match("$excludePattern", $item->title)) {
$filteredTitle=htmlspecialchars("$item->title");
$filteredTitle=str_replace("$username: ","",$filteredTitle);
//Convert the time zone in China --转成中国时区
date_default_timezone_set('Asia/Shanghai');
$i++;

if($i>$count)
{
break;
}
?>
<li><?php echo $filteredTitle; ?>
(<?php echo date("Y-m-d H:i:s",strtotime($item->pubDate)); ?>)</li>
<?php } } ?>
<div align="right">
<a href="http://twitter.com/xjb" target="_blank">更多...</a></div>
<!-- my tritter -->

源代码
复制代码 代码如下:

<!-- my tritter -->
<?php

$username='xjb'; //change this to your twitter username --修改为你的twitter 用户名
$feedURL='http://twitter.com/statuses/user_timeline/'.$username.'.rss';
$excludePattern='/'.$username.': @/'; //excludes any @replies --排除 @replies 内容
$count=5;// show count
$i=0;

if(!$xml=simplexml_load_file($feedURL)){
trigger_error('Error',E_USER_ERROR);
}
foreach($xml->channel->item as $item) {
if ( ! preg_match("$excludePattern", $item->title)) {
$filteredTitle=htmlspecialchars("$item->title");
$filteredTitle=str_replace("$username: ","",$filteredTitle);
date_default_timezone_set('Asia/Shanghai'); //Convert the time zone in China --转成中国时区
$i++;

if($i>$count)
{
break;
}
?>

<li><?php echo $filteredTitle; ?>(<?php echo date("Y-m-d H:i:s",strtotime($item->pubDate)); ?>)</li>
<?php } } ?>
<div align="right"><a href="http://twitter.com/xjb" target="_blank">更多...</a></div>
<!-- my tritter -->

相关文章

php mssql 时间格式问题

当然是在程序里解决比较灵活,例如: “select convert(char,日期字段,120) as date2 from table” convert(char,date,N)输出的...

PHP批斗大会之缺失的异常详解

故事的开始 这几天观察错误日志发现有一个数据反序列化的notice错误,实际情况我是从缓存中读取数据然后反序列化,因为反序列化失败,所以实际每次都是去数据库取的值。背后性能影响还是挺大...

php使用filter_var函数判断邮箱,url,ip格式示例

本文实例讲述了php使用filter_var函数判断邮箱,url,ip格式。分享给大家供大家参考,具体如下: 以前使用php的时候还不知道有过滤器filter这玩意,那时候判断邮箱、ur...

PHP与SQL注入攻击[一]

Haohappy http://blog.csdn.net/Haohappy2004 SQL注入攻击是黑客攻击网站最常用的手段。如果你的站点没有使用严格的用户输入检验,那么非常容易遭到S...

PHP5.6.8连接SQL Server 2008 R2数据库常用技巧分析总结

PHP5.6.8连接SQL Server 2008 R2数据库常用技巧分析总结

本文实例讲述了PHP5.6.8连接SQL Server 2008 R2数据库常用技巧。分享给大家供大家参考,具体如下: 用到的工具: 1.JetBrains PhpStorm (编写p...