现在的位置: 首页 > 综合 > 正文

file_get_contents和curl函数用法

2014年03月10日 ⁄ 综合 ⁄ 共 1365字 ⁄ 字号 评论关闭

file_get_contents ()很简单,但是有的服务器.ini设置如果关闭allow_url_fopen,这个就失效了,一般个人可以设置,但是如果是虚拟主机就不在自己掌控范围内了。但是 是另外一个打开远程页面的内容的函数如下:

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);
?>

当然此功能也有被关闭的可能。

function getcon(){
$url=http://localhost:8080/test/test.txt;
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}

在用php的时候,做采集网页,收集内容,我们大多数需要用到file_get_contents这个函数.

但是这个函数在循环使用的时候,偶尔会失效.

这时候,我们可以使用curl函数来代替!

有时候curl,file_get_contents测试的时候,执行时间和效率都相差无几,但有时却因为file_get_contents不及curl。

  1. file_get_contents 每次请求都会重新做DNS查询,并不对DNS信息进行缓存。但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS 查询。这大大减少了DNS查询的次数。所以CURL的性能比file_get_contents 好很多。
  2. file_get_contents在请求HTTP时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。
  3. file_get_contents函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。
  4. curl可以模拟多种请求,例如:POST数据,表单提交等,用户可以按照自己的需求来定制请求。而file_get_contents只能使用get方式获取数据。

 

所以,一般来说,

file_get_cotents 读取本地文件是首选

curl_init 读取远程文件是首选

另外,如果有的服务器php.ini设置如果关闭allow_url_fopen,file_get_contents这个函数就失效了.

抱歉!评论已关闭.