做过好多抓取别家网站内容的产品,习惯了使用方便快捷的file_get_contents函数,但是总是会遇到获取失败的问题,尽管按照手册中的例子设置了超时,可多数时候不会奏效:
$config['context'] = stream_context_create(array(‘http’ => array(‘method’ => “GET”,
’timeout’ => 5//这个超时时间不稳定,经常不奏效
)
));
这时候,看一下服务器的连接池,会发现一堆类似的错误,让你头疼万分:
file_get_contents(http://***
): failed to open stream…
不得已,安装了curl库,写了一个函数替换:
function curl_file_get_contents($durl){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $durl);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
如此,除了真正的网络问题外,没再出现任何问题。
这是别人做过的关于curl和file_get_contents的测试:
file_get_contents抓取google.com需用秒数:
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
curl使用的时间:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594
差距很大吧?呵呵,从我使用的经验来说,这两个工具不只是速度有差异,稳定性也相差很大。建议对网络数据抓取稳定性要求比较高的朋友使用上面的curl_file_get_contents函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦!
转载来之:http://www.71j.cn/archives/140
分享到:
相关推荐
分享一个实际在用的函数: 复制代码 代码如下: /*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/ function curl_get_contents($url,$timeout=1) { $curlHandle = curl_init(); curl_...
本文实例讲述了php中file_get_contents与curl性能比较分析。分享给大家供大家参考。具体如下: 在php中如果不仔细的去分析性能会发现file_get_contents与curl两个同很多共同点的,他们都可以采集文件打开文件,但是...
本篇文章是对file_get_contents与curl效率及稳定性进行了详细的分析介绍,需要的朋友参考下
下面是file_get_contents和curl两个函数同样功能的不同写法file_get_contents函数的使用示例:复制代码 代码如下:< ?php$file_contents = file_get_contents(‘https://www.jb51.net’);echo $file_...
file_get_contents代替使用curl其实不多见了,但有时你碰到服务器不支持curl时我们可以使用file_get_contents代替使用curl,下面看个例子。 当用尽一切办法发现 服务器真的无法使用curl时。或者curl不支持https时。...
如果你使用file_get_contents获取远程文件内容返回为空或提示该函数不可用,也许本文能帮到你! 使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置allow_url_fopen = On,allow_url...
下面是file_get_contents和curl两个函数同样功能的不同写法file_get_contents函数的使用示例:复制代码 代码如下:< ?php$file_contents = file_get_contents(‘https://www.jb51.net’);echo $file_...
curl多用于互联网网页之间的抓取,fopen多用于读取文件,而file_get_contents多用于获取静态页面的内容。 1. fopen /file_get_contents 每次请求都会重新做DNS查询,并不对DNS信息进行缓存。但是CURL会自动对DNS信息...
另外,curl的性能比file_get_contents高,所以用curl重写file_get_contents function _file_get_contents($s) { $ret = ; $ch = curl_init($s); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch...
错误: Warning: fopen() [function.fopen]: Unable to find the wrapper “https” – did you forget to enable it ...3.如果服务器你不能修改配置的话,那么就使用curl函数来替代file_get_contents函数,
$ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //在需要用户检测的网页里需要增加...
抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_content那么简单,再就是需求也不大,所以没有学习使用curl。...
今天小编就为大家分享一篇解决PHP curl或file_get_contents下载图片损坏或无法打开的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧