首先祝大家龙年快乐,高高兴兴过大年;最近闲在家里看着首页位置很空旷,想把微博消息直接调用到首页上去,这样以后有实时消息就可以发微博并直接在首页上看到了。经过3天的改进,首页已经可以把腾讯微博、新浪微博的广播消息同步出来。
腾讯微博官方提供了API给我们调用,我们就用它提供的json数据接口来实现微博调用:
function vita_get_url_content($getjson) {
if(function_exists('curl_init')) {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $getjson);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
} else {
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 5 //设置一个超时时间,单位为秒
)
)
);
$file_contents = file_get_contents($getjson, 0,$ctx);
}
return $file_contents;
}
然后把获取到的变量通过json_decode()转换为数组:
$weibo = json_decode($content, true); $arr = $weibo['data'];
然后使用下面的关键代码,进行数组处理:
if($arr) {
//array_reverse倒序数组
foreach(array_reverse($arr) as $item) {
$time=$item['timestamp'];
if (in_array((string)$time, $time_arr, true)) {
echo "---------未更新|不写入----------";
}else{
$type="tenxun";
switch ((int)$item['type']) {
case 1:
$content=replace_url($item['content']);
// my_sqlite($type,$content,$time);
break;
case 2:
$content='转播:'.replace_url($item['content']).''.$item['source']['nick'].''.replace_url($item['source']['content']);
break;
case 4:
$content=$item['nick'].' 对'.$item['source']['nick'].' 说: '.replace_url($item['content']).''.$item['source']['nick'].' '.replace_url($item['source']['content']);
break;
case 5:
$content='说:'.replace_url($item['content']);
break;
default:
break;
} //switch end
my_sqlite($type,$content,$time);
} //else end
} //forsearch end
}else{
echo '暂时无法读取腾讯微博数据';
}
上面函数首先对处理好的数组进行判断,如果数组正常,则对数组循环调用,把每个调用值输出到变量$item中,变量$item包含了所以需要输出的值:微博用户名、微博内容、发布的时间等。
再加上一些css样式处理,首页实时更新微博的功能就实现了。
来看一下预览效果(http://malu.me/ ):
下一篇文章将介绍新浪微博的数据处理。

