有些主机服务商把php的allow_url_fopen选项是关闭了,就是没法直接使用file_get_contents来获取远程web页面的内容。那就是可以使用另外一个函数curl
本文#来源gaodai.ma#com搞##代!^码7网
搞代gaodaima码
。
下面是file_get_contents和curl两个函数同样功能的不同写法
file_get_contents函数的使用示例:
< ?php<BR>$file_contents = file_get_contents('http://www.gaodaima.com');<BR>echo $file_contents;<BR>?><BR>
换成curl函数的使用示例:
< ?php<BR>$ch = curl_init();<BR>$timeout = 5;<BR>curl_setopt ($ch, CURLOPT_URL, 'http://www.gaodaima.com');<BR>curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);<BR>curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);<BR>$file_contents = curl_exec($ch);<BR>curl_close($ch);<BR>echo $file_contents;<BR>?><BR>
利用function_exists函数来判断php是否支持一个函数可以轻松写出下面函数
< ?php<BR>function vita_get_url_content($url) {<BR>if(function_exists('file_get_contents')) {<BR>$file_contents = file_get_contents($url);<BR>} else {<BR>$ch = curl_init();<BR>$timeout = 5;<BR>curl_setopt ($ch, CURLOPT_URL, $url);<BR>curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);<BR>curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);<BR>$file_contents = curl_exec($ch);<BR>curl_close($ch);<BR>}<BR>return $file_contents;<BR>}<BR>?><BR>
其实上面的这个函数还有待商榷,如果你的主机服务商把file_get_contents和curl都关闭了,上面的函数就会出现错误。