博客导读网

一个让你随便看看的地方

分享比file_get_contents稳定的curl_get_contents

推荐
9Enjoy

分享一个实际在用的函数:
/*比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.9enjoy.com');

相信使用过file_get_contents函数的朋友都知道,当获取的$url访问不了时,会导致页面漫长的等待,甚至还能导致PHP进程占用CPU达100%,因此这个函数就诞生了。curl的一些常识介绍

保留原file_get_contents函数的原因是当读取本地文件时,用原生的file_get_contents显然更合适。

另来自张宴的file_get_contnets的优化,具体可看:http://blog.s135.com/file_get_contents
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。
$ctx = stream_context_create(array(  
   'http' => array(  
       'timeout' => 1 //设置一个超时时间,单位为秒  
       )  
   )  
);  
file_get_contents("http://www.9enjoy.com/", 0, $ctx);


另外,据不完全测试,使用curl获取页面比用file_get_contents稳定的多。


Tags - ,
原文地址:http://item.feedsky.com/~feedsky/9enjoy/~1348731/593284745/1353774/1/item.html

9Enjoy的其他文章
json_encode后的中文不编码成unicode ArrayOf_xsd_string格式在php下的处理
win2003服务器使用WPS的COM组件的一些问题解决 Trying to clone an uncloneable object of class Imagic的解决
PHP警告Cannot use a scalar value as an array的解决 首选域的选择(根域名如何正确的跳转到www域名)
mongodb在windows下的安装 你见过ORDER BY -title DESC这种用法吗?
sphinx用c写的扩展性能还不如php写的api? 提高define性能的php扩展hidef的安装和使用
更多...

© 2010 博客导读网 BlogABC.NET 本站所有内容皆由网友推荐而来,所有博文的版权归原作者所有,如有冒犯,请邮件告知。uncracker#gmail.com