PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

深入file_get_contents与curl函数的详解_php技巧

原创
2016-05-17 08:58:35 1067浏览

有些主机服务商把php的allow_url_fopen选项是关闭了,就是没法直接使用file_get_contents来获取远程web页面的内容。那就是可以使用另外一个函数curl。
下面是file_get_contents和curl两个函数同样功能的不同写法
file_get_contents函数的使用示例:

复制代码 代码如下:

$file_contents = file_get_contents('http://www.jb51.net');
echo $file_contents;
?>

换成curl函数的使用示例:
复制代码 代码如下:

$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.jb51.net');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>

利用function_exists函数来判断php是否支持一个函数可以轻松写出下面函数
复制代码 代码如下:

function vita_get_url_content($url) {
if(function_exists('file_get_contents')) {
$file_contents = file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}
?>

其实上面的这个函数还有待商榷,如果你的主机服务商把file_get_contents和curl都关闭了,上面的函数就会出现错误。
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。