您好,欢迎访问一九零五行业门户网

PHP CURL或file_get_contents获取网页标题的代码

php curl与file_get_contents函数都可以获取远程服务器上的文件保存到本地,但在性能上面两者完全不在同一个级别,下面我先来介绍php curl或file_get_contents函数应用例子,然后再简单的给各位介绍一下它们的一些小区别吧。
推荐方法 curl获取
 代码如下 复制代码
使用file_get_contents
 代码如下 复制代码
看看file_get_contents性能
1)fopen/file_get_contents 每次请求远程url中的数据都会重新做dns查询,并不对dns信息进行缓存。但是curl会自动对dns信息进行缓存。对同一域名下的网页或者图片的请求只需要一次dns 查询。这大大减少了dns查询的次数。所以curl的性能比fopen/file_get_contents 好很多。
2)fopen/file_get_contents在请求http时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。(设置header头应该可以)
3)fopen/file_get_contents函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。
4)curl可以模拟多种请求,例如:post数据,表单提交等,用户可以按照自己的需求来定制请求。而fopen/file_get_contents只能使用get方式获取数据。
5)fopen/file_get_contents 不能正确下载二进制文件
6)fopen/file_get_contents 不能正确处理ssl请求
7)curl 可以利用多线程
8)使用 file_get_contents 的时候如果 网络出现问题, 很容易堆积一些进程在这里
9)如果是要打一个持续连接,多次请求多个页面。那么file_get_contents就会出问题。取得的内容也可能会不对。所以做一些类似采集工作的时候,肯定就有问题了。对做采集抓取的用curl,如果还有同不相信下面我们再做个测试
curl与file_get_contents性能对比php源代码如下:
1829.php
 代码如下 复制代码
code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}
function getcity($ip)
{
    $url=http://ip.taobao.com/service/getipinfo.php?ip=.$ip;
    $ipinfo=json_decode(file_get_contents($url));
    if($ipinfo->code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}
// for file_get_contents
$starttime=explode(' ',microtime());
$starttime=$starttime[0] + $starttime[1];
for($i=1;$i{
   echo getcity(121.207.247.202).;
}
$endtime = explode(' ',microtime());
$endtime = $endtime[0] + $endtime[1];
$totaltime = $endtime - $starttime;
echo 'file_get_contents:'.number_format($totaltime, 10, '.', ). seconds;
//for curl
$starttime2=explode(' ',microtime());
$starttime2=$starttime2[0] + $starttime2[1];
for($i=1;$i{
   echo getcitycurl('121.207.247.202').;
}
$endtime2 = explode(' ',microtime());
$endtime2=$endtime2[0] + $endtime2[1];
$totaltime2 = $endtime2 - $starttime2;
echo curl:.number_format($totaltime2, 10, '.', ). seconds;
?>
测试访问
file_get_contents速度:4.2404510975 seconds
curl速度:2.8205530643 seconds
curl比file_get_contents速度快了30%左右,最重要的是服务器负载更低.
其它类似信息

推荐信息