file_get_contents与curl获取远程内容对比
部分主机服务商可能禁用了php的allow_url_fopen配置项,导致无法直接通过file_get_contents读取远程网页内容。此时可切换使用curl函数作为替代方案。
以下是file_get_contents与curl实现相同功能的代码对照:
file_get_contents函数的基本调用示例如下:
具体代码实现为:
<?php
$file_contents = file_get_contents('https://www.jb51.net');
echo $file_contents;
?>
若替换为curl函数,其使用示例如下:
对应代码如下:
<?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'https://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功能,该函数执行时将引发错误。