PHP中curl_init和file_get_contents配合使用
2012-10-01 10:11
615 查看
在PHP源码的扩展库中默认存在curl的扩展,编译就可以直接安装。但之前测试过一个远程xml获取代码,使用了curl函数,在刚搭建的vps上无法运行。通过探针查看,发现curl扩展并没有安装上去。
本来可以重新在apache上添加curl扩展的,但是考虑到以后有些主机并不一定支持curl,为了增加程序的兼容性,于是对源代码做了如下更改:
以上函数直接使用,$getxml变量传递URL信息,返回变量$file_contents传出获取到的内容。
对于判断函数还可以这样写:
优先判断是否支持file_get_contents,这样一来可以根据需要自己调整。两函数均进行了超时控制,防止远程链接失效而导致服务器负载过大。
本来可以重新在apache上添加curl扩展的,但是考虑到以后有些主机并不一定支持curl,为了增加程序的兼容性,于是对源代码做了如下更改:
function malu_get_url_content($getxml) { if(function_exists('curl_init')) { $ch = curl_init(); $timeout = 60; //curl超时时间 curl_setopt ($ch, CURLOPT_URL, $getxml); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); echo " (curl) "; } else { $ctx = stream_context_create(array( 'http' => array( 'timeout' => 60 //设置一个超时时间,单位为秒 ) ) ); $file_contents = file_get_contents($getxml, 0,$ctx); echo " (file_get) "; } return $file_contents; }
以上函数直接使用,$getxml变量传递URL信息,返回变量$file_contents传出获取到的内容。
对于判断函数还可以这样写:
if(function_exists('file_get_contents')) {
优先判断是否支持file_get_contents,这样一来可以根据需要自己调整。两函数均进行了超时控制,防止远程链接失效而导致服务器负载过大。
相关文章推荐
- PHP无法使用file_get_contents或者curl_init()函数解决办法
- PHP使用file_get_contents或curl请求https的域名内容为空或Http 505错误的问题排查方法
- PHP使用curl替代file_get_contents
- nginx+fastcgi php 使用file_get_contents、curl、fopen读取localhost本站点.php异常的情况
- PHP使用curl替代file_get_contents
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- PHP使用curl替代file_get_contents
- PHP使用curl替代file_get_contents
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- PHP使用curl替代file_get_contents
- php采用file_get_contents代替使用curl实例
- windows nginx使用file_get_contents、fopen、curl访问php文件造成阻塞的解决办法
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- 使用PHP的curl扩展实现跨域post请求,以及file_get_contents()百度短网址例子
- php采用file_get_contents代替使用curl实例
- file_get_contents("php://input")的使用方法
- PHP利用Curl、socket、file_get_contents POST数据
- PHP下通过file_get_contents\curl的方法实现获取远程网页内容(别忘了还有PhpRPC)
- file_get_contents("php://input")的使用方法