分享一个实际在用的函数:
复制代码 代码如下:
/*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/
function curl_get_contents($url,$timeout=1) {
$curlHandle = curl_init();
curl_setopt( $curlHandle , CURLOPT_URL, $url );
curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout );
$result = curl_exec( $curlHandle );
curl_close( $curlHandle );
return $result;
}
$hx = curl_get_contents('http://www.jb51.net');
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。curl的一些常识介绍
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:http://www.jb51.net/article/28030.htm
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
复制代码 代码如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //设置一个超时时间,单位为秒
)
)
);
file_get_contents("http://www.jb51.net/", 0, $ctx);
另外,据不完全测试,使用curl获取页面比用file_get_contents稳定的多。
复制代码 代码如下:
/*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/
function curl_get_contents($url,$timeout=1) {
$curlHandle = curl_init();
curl_setopt( $curlHandle , CURLOPT_URL, $url );
curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout );
$result = curl_exec( $curlHandle );
curl_close( $curlHandle );
return $result;
}
$hx = curl_get_contents('http://www.jb51.net');
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。curl的一些常识介绍
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:http://www.jb51.net/article/28030.htm
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
复制代码 代码如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //设置一个超时时间,单位为秒
)
)
);
file_get_contents("http://www.jb51.net/", 0, $ctx);
另外,据不完全测试,使用curl获取页面比用file_get_contents稳定的多。
关键字词:
相关文章
- php使用file_get_content设置请求header参数
- php运行提示Warning require() open_basedir restriction in effect. File
- thinkphp3.2获取当前操作的模块名控制器方法名称_编程资料分享
- PHP explode换行分割字符串_编程资料分享
- echarts多个报表宽度自适应解决办法_编程资料分享
- dedecms后台文章发布标题自动生成tags和关键词详解_编程资料分享
- PHP 计算两个时间日期相差的天数方法_编程资料分享
- thinkphp 3.2 where 字符串条件处理_编程资料分享
- php curl获取header和body内容_编程资料分享
- PHP生成MySQL数据字典 数据表结构_编程资料分享