开发者社区> 问答> 正文

PHP获取关键词的百度排名,file_get_contents老提示failed?报错

PHP获取关键词的百度排名,file_get_contents老提示failed to open stream: HTTP request failed!请问如何解决,看了好多网上资料,配置php.in还是不行

下面是我从网上找到的一段代码

<?php
function getbaiduRank($key,$weburl)//关键词,网址
{
   //$newkey = iconv ('utf-8','gb2312',$key);
 $newkey =$key;
 $newkey = urlencode($newkey);
 $url = "http://www.baidu.com/s?ie=gb2312&wd=$newkey&rn=30";
 $content = str_replace('<table border="0" cellpadding="0" cellspacing="0"',
'<table cellpadding="0" cellspacing="0"',file_get_contents($url));
 $arr = array();
 $arr = explode ('class=m>推广',$content);//排除推广  
 $shuliang=count($arr);  
 //print_r ($arr[$shuliang-1]);
 $arr = explode ('<br clear=all>',$arr[$shuliang-1]);//去除尾部  
 $arr = explode ('<table cellpadding="0" cellspacing="0" id="',$arr[0]);
 $shuliang=count($arr);
 $paiming=0;
 for ($i=1;$i<$shuliang;$i++){if (strpos($arr[$i],$weburl)>0) {$paiming=$i;break;}}
 echo "关键词:".urldecode($newkey)."|网站:".$weburl."百度排名:".$paiming;
}
getbaiduRank('oscphp','http://www.oscphp.com');
?>

运行后就报错

Warning: file_get_contents(http://www.baidu.com/s?ie=gb2312&wd=oscphp&rn=30): failed to open stream: HTTP request failed! in E:\xampp\htdocs\ceshi.php on line 8 关键词:oscphp|网站:http://www.oscphp.com百度排名:0

展开
收起
爱吃鱼的程序员 2020-06-22 22:03:00 515 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    用curl<spanstyle="font-family:微软雅黑,Verdana,sans-serif,宋体;font-size:14px;line-height:normal;background-color:#F9F9F9;">你要是抓取数据的话,最好用curl,file_get_contents不太适合你说的这种场合,比较适合读取本地文件

    file_get_contents函数运行不正常的话检查下服务器的网络配置

    例如防火墙 网卡什么的..

    以前碰到过双网卡配置不当导致的file_get_contents函数出现你这样的错误

    file_get_contents本来就不是设计来获取网上的数据的

    curl更适合你的要求

    2020-06-22 22:03:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
PHP安全开发:从白帽角度做安全 立即下载
PHP 2017.北京 全球开发者大会——高可用的PHP 立即下载
复杂PHP系统性能瓶颈排查及优化 立即下载