前面两篇文章提到了国内两大微博的json数据调用,之所以分开写,是因为它们的调用方式有点不同。今天要讲到我们最伟大的微博Twitter的json数据调用,它的数据调用却是结合了国内2大微博的优点,也可以说是国内微博模仿了Twitter。不管谁模仿谁,调用Twitter的json数据是今天的正题,下面看源码:
Twitter官方给出的接口调用非常简单,几乎可以10行代码搞定,不过为了更高效,我使用了缓存,方式刷新次数过猛而对数据调用产生影响:
$username = 'username';
$tweet_count = '20';
$getjson = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=' . $username . '&count=' . $count . '&include_entities=1&include_rts=1';
$expire = 120; //过期时间,单位秒,2分钟
$cache_file = './sqlite_twitter.dat'; //缓存文件
$arr = array();
clearstatcache();
if (file_exists($cache_file) && time() <= (filemtime($cache_file) + $expire)) {
//缓存文件存在且未过期则直接读取
$arr = unserialize(file_get_contents($cache_file));
echo "********缓存存在且未过期,直接读取缓存数据********";
$timelost = $expire - (time() - filemtime($cache_file));
echo "***********Twitter距离下次更新还剩 $timelost 秒***********";
}else{
//缓存文件不存在或已过期则读取json数据处理并缓存
$content = file_get_contents($getjson); //远程调用
$arr = json_decode($content, true);
if($arr) {
file_put_contents($cache_file, serialize($arr)); //写入缓存文件
echo "*********读取Twitter接口数据成功*********";
}else{
echo "**error**读取Twitter接口数据失败**error**";
$arr = unserialize(file_get_contents($cache_file));
echo "******************|*******************";
echo "******************|*******************";
echo "******************|*******************";
echo "******************|*******************";
echo "******************V*******************";
echo "*********调用缓存数据数据成功*********";
}
}
以上代码就可以直接调用到Twitter的数据,并保存在数组$arr中,接下来只要包数组中的数据调用显示就完成了:
if($arr){
foreach ($arr as $tweet) {
$datetime = $tweet[created_at];
$time = strtotime($datetime);
$content = str_replace("'","''",$tweet[text]);
echo "$content | $time <br>";
}
}else{
echo "twitter 数据获取失败!";
}
通过php循环输出数组,把Twitter的内容就全部的输出显示了。
其中$content = str_replace(“‘”,”””,$tweet[text]); 是把字符串中带单引号的字符转换成2个单引号,这是因为在写入sqlite是会用到,不写入sqlite的朋友可以把该转换去掉。
