比file_get_contents稳定的curl_get_contents分享
2012-01-11 00:00
375 查看
分享一个实际在用的函数:
相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。curl的一些常识介绍
保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。
另来自张宴的file_get_contnets的优化,具体可看:/article/1268665.html
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
另外,据不完全测试,使用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的优化,具体可看:/article/1268665.html
同样是设置超时时间来解决这个问题。如果没装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稳定的curl_get_contents分享
- file_get_contents是打工文件或URL获取内容的方法,比其稳定的还有curl_get_contents
- 比file_get_contents稳定的curl_get_contents
- php读取网络文件 curl, fsockopen ,file_get_contents 几个方法的效率对比
- php中file_get_contents与curl性能比较分析
- file_get_contents与curl的区别
- PHP中几种HTTP请求的实现方法及比较: file_get_contents vs. cURL vs. PECL_HTTP
- 比 file_get_contents() 更优的 cURL 详解(附实例)
- 解决php无法通过file_get_contents或curl采集页面内容
- php中file_get_contents与curl性能比较分析
- 分享一个post/get curl 合体函数封装
- fopen,file_get_contents,curl
- curl socket file_get_contents ph…
- php读取网络文件 curl, fsockopen ,file_get_contents 几个方法的效率对比
- fsockopen/curl/file_get_contents效率比较
- file_get_contents与curl效率及稳定性问题
- file_get_contents,fopen,curl 获取远程页面
- php读取网络文件 curl, fsockopen ,file_get_contents 几个方法的效率对比
- curl和file_get_contents 区别以及各自的优劣