]*?>'si","",$table);
$table = preg_replace("']*?>'si","",$table);
$table = preg_replace("']*?>'si","",$table);
$table = str_replace(" |
","{tr}",$table);
$table = str_replace("","{td}",$table);
//去掉 HTML 标记
$table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
//去掉空白字符
$table = preg_replace("'([rn])[s]+'","",$table);
$table = str_replace(" ","",$table);
$table = str_replace(" ","",$table);
$table = explode('{tr}', $table);
array_pop($table);
foreach ($table as $key=>$tr) {
// 自己可添加对应的替换
$tr = str_replace("nn","",$tr);
$td = explode('{td}', $tr);
array_pop($td);
$td_array[] = $td;
}
return $td_array;
}
3.返回数据
爬取整理数据并返回以便前端调用:
$html = getUrlContent("https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6");
$table = getTable($html);
$table = array_slice($table,2); # 把前面多余部分截掉
echo json_encode($table);
至此,可将以上代码整合为一个php文件,设名为“weibo.php”,以待前端通过ajax的方式调用。
三、数据可视化
实不相瞒:前端咱不行,但四处搬砖、东拼西凑还是比较拿手的~ 现学了echarts.js,再看看网上前辈大佬们的演示,最终还是“凑”了出来。
1.画柱状图
利用echarts.js在画布上画出统计的柱状图:
function CreateBar(keywords,value){
//初始化echarts实例
var myChart = echarts.init(document.getElementById('chartmain'));
myChart.on('click',function(param){
window.open('#');
});
//指定图标的配置和数据
var option = {
title:{
text:''
},
tooltip:{},
grid:{
top:"15%",
left:"16%",
bottom:"5%"
},
legend:{
data:['热搜词']
},
xAxis:{
},
yAxis:{
data:keywords
},
series:[{
name:'搜索量',
type:'bar',
itemStyle: {
normal: {
color: '#ff9406'
}
},
data:value
}]
};
myChart.setOption(option);
}
这里需要两个参数(两个Array),即热搜词和搜索量,而它们得通过ajax的方式向后端发送请求获取。
2.ajax请求数据
通过ajax的方式向后端发起请求(即之前提到的weibo.php),以获得数据:
function GetData(){
$.ajax({
type: "post", //数据提交方式(post/get)
url: "weibo.php", //提交到的url
dataType: "json", //返回的数据类型格式
success: function(msg){
//返回成功的回调函数
if(msg!=''){
var data = eval(msg); //将返回的json数据进行解析,并赋给data
var keywords = [];
var value = [];
for(var i=0; i < 20; i++){ // 取TOP20
keywords.push(data[i][1].split('n')[0]);
value.push(Number(data[i][1].split('n')[1]));
}
CreateBar(keywords.reverse(),value.reverse());
setInterval("GetData()",10000); // 间隔10S
}
},
error:function(msg){
//返回失败的回调函数
console.log(msg);
setInterval("GetData()",30000); // 间隔30S
}
});
}
注:这里用了**setInterval()**的方法来实现定时发送异步请求,以实现实时监控。
四、效果展示
经过不懈的尝试和修改,最后达到了一个还算比较满意的效果,大概就是这个样子啦:
写在最后
实现这个目标,还有一种思路:先用脚本(如python)获取数据并存入数据库,然后再通过读取数据库来进行数据展示,这样也许更加灵活而且在搜集到一定量的数据后还能尝试更多有趣的统计分析。
以上就是关于PHP实现微博热搜实时监控平台教程的全部内容了,感兴趣的小伙伴记得点击关注哦。