当使用php函数 file_get_contents抓取远程网页时,如果连接超时将会输出一个Fatal Error,结果导致下面的代码不能运行,一般可采取两个解决方案:
1. 利用file_get_contents()第三个参数
PHP代码
来源:http://hi.baidu.com/baijunhui/blog/item/918662a8b90e10b9ca130ca5.html
1. 利用file_get_contents()第三个参数
PHP代码
<?php
$url = "http://172.16.0.40/die.php";
$ctx = stream_context_create(array(
'http' => array('timeout' => 10)
)
);
$result = @file_get_contents($url, 0, $ctx);
if($result){
var_dump($result);
}else{
echo " Buffer is empty";
}
?>
$url = "http://172.16.0.40/die.php";
$ctx = stream_context_create(array(
'http' => array('timeout' => 10)
)
);
$result = @file_get_contents($url, 0, $ctx);
if($result){
var_dump($result);
}else{
echo " Buffer is empty";
}
?>
<?php
$url = "http://172.16.0.40/die.php";
try {
echo date('Y-m-d h:i:s');
echo "<br/>";
//$buffer = file_get_contents($url);
$buffer = joy_file_get_contents($url);
echo date('Y-m-d h:i:s');
if(empty($buffer)) {
echo " Buffer is empty";
} else {
echo " Buffer is not empty";
}
} catch(Exception $e) {
echo "error ";
}
function joy_file_get_contents($url, $second = 5){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
$url = "http://172.16.0.40/die.php";
try {
echo date('Y-m-d h:i:s');
echo "<br/>";
//$buffer = file_get_contents($url);
$buffer = joy_file_get_contents($url);
echo date('Y-m-d h:i:s');
if(empty($buffer)) {
echo " Buffer is empty";
} else {
echo " Buffer is not empty";
}
} catch(Exception $e) {
echo "error ";
}
function joy_file_get_contents($url, $second = 5){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
来源:http://hi.baidu.com/baijunhui/blog/item/918662a8b90e10b9ca130ca5.html
作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/3411/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!
评论列表