我以前是用curl抓取页面的,curl里面有个参数可以设置抓取页面的超时时间,例如:
curl_setopt($ch,CURLOPT_TIMEOUT,30); // 设置超时限制防止死循环不知道用file_get_contents 如果设置超时,请大家指点。谢谢
curl_setopt($ch,CURLOPT_TIMEOUT,30); // 设置超时限制防止死循环不知道用file_get_contents 如果设置超时,请大家指点。谢谢
$try_count = 3;
for($i=0; $i<3 and $html === false; $i++){
$html = file_get_contents($url);
}
一、增加超时的时间限制
这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的。真正的修改file_get_contents延时可以用resource $context的timeout参数:
代码如下:
$opts = array(
'http'=>array(
'method'=>”GET”,
'timeout'=>60,
)
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.phpzixue.cn', false, $context);
fpassthru($fp);二、一次有延时的话那就多试几次
有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
复制代码 代码如下:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http://www.phpzixue.cn'))===FALSE) $cnt++;