PHP CURL与file_get_contents函数都可以获取远程服务器上的文件保存到本地,但在性能上面两者完全不在同一个级别,下面我先来介绍PHP CURL或file_get_contents函数应用例子,然后再简单的给各位介绍一下它们的一些小区别吧。

推荐方法 CURL获取

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$c = curl_init();
$url = 'www.jb51.net';
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($c);
curl_close($c);
$pos = strpos($data,'utf-8');
if($pos===false){$data = iconv("gbk","utf-8",$data);}
preg_match("/<title>(.*)<\/title>/i",$data, $title);
echo $title[1];
?>

使用file_get_contents

1
2
3
4
5
6
7
8
9
<?php
$content=file_get_contents("http://www.jb51.net/");
$pos = strpos($content,'utf-8');
if($pos===false){$content = iconv("gbk","utf-8",$content);}
$postb=strpos($content,'<title>')+7;
$poste=strpos($content,'</title>');
$length=$poste-$postb;
echo substr($content,$postb,$length);
?>

看看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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/**
* 通过淘宝IP接口获取IP地理位置
* @param string $ip
* @return: string
**/
function getCityCurl($ip)
{
$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);
$ipinfo=json_decode($file_contents);
if($ipinfo->code=='1'){
return false;
}
$city = $ipinfo->data->region.$ipinfo->data->city;
return $city;
}
function getCity($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<=10;$i++)
{
echo getCity("121.207.247.202")."</br>";
}
$endTime = explode(' ',microtime());
$endTime = $endTime[0] + $endTime[1];
$totalTime = $endTime - $startTime;
echo 'file_get_contents:'.number_format($totalTime, 10, '.', "")." seconds</br>";
//for curl
$startTime2=explode(' ',microtime());
$startTime2=$startTime2[0] + $startTime2[1];
for($i=1;$i<=10;$i++)
{
echo getCityCurl('121.207.247.202')."</br>";
}
$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%左右,最重要的是服务器负载更低.

ps:php函数file_get_contents与curl效率及稳定性问题

习惯了使用方便快捷的file_get_contents函数抓取别家网站内容,但是总是会遇到获取失败的问题,尽管按照手册中的例子设置了超时,可多数时候不好使:

$config['context'] = stream_context_create(array('http' => array('method' => "GET",'timeout' => 5)));
'timeout' => 5//这个超时时间不稳定,经常不好使。这时候,看一下服务器的连接池,会发现一堆类似下面的错误,让你头疼万分:

file_get_contents(http://***): failed to open stream…

不得已,安装了curl库,写了一个函数替换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
//curl_setopt($ch,CURLOPT_HEADER,1); //是否显示头部信息
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); //用户访问代理 User-Agent
curl_setopt($ch, CURLOPT_REFERER,_REFERER_); //设置 referer
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟踪301
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
$r = curl_exec($ch);
curl_close($ch);
return $r;
}

如此,除了真正的网络问题外,没再出现任何问题。

这是别人做过的关于curl和file_get_contents的测试:

file_get_contents抓取google.com需用秒数:

2.31319094
2.30374217
2.21512604
3.30553889
2.30124092

curl使用的时间:

0.68719101
0.64675593
0.64326
0.81983113
0.63956594

差距很大吧?呵呵,从我使用的经验来说,这两个工具不只是速度有差异,稳定性也相差很大。建议对网络数据抓取稳定性要求比较高的朋友使用上面的 curl_file_get_contents函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦!

PHP CURL或file_get_contents获取网页标题的代码及两者效率的稳定性问题的更多相关文章

  1. php正则获取网页标题、关键字、网页描述代码

    php正则获取网页关键字,代码如下: function get_keywords($html) { $html=strtolower($html); preg_match("@<hea ...

  2. Python2获取网页标题

    Python获取网页标题 使用Python2.x的urllib2和lxml,速度应该还快于BeautifulSoup4(话说回来,为什么大家都要用BS4呢?一个XPATH不就完了吗) 没有安装过的,用 ...

  3. curl 或 file_get_contents 获取需要授权页面的方法

    原文:http://blog.csdn.net/fdipzone/article/details/44475801 红色字体部分是加上自己的注释,整理了一下. 今天因工作需要,需要用 curl / f ...

  4. 浅谈 php 采用curl 函数库获取网页 cookie 和 带着cookie去访问 网页的方法!!!!

    由于近段时间帮朋友开发一个能够查询正方教务系统的微信公众平台号.有所收获.这里总结下个人经验. 开讲前,先吐槽一下新浪云服务器,一个程序里的   同一个函数  在PC测试可以正常运行,在它那里就会挂的 ...

  5. 【Excel】获取网页标题的VBA

    在宏录制,完成后可以直接在网格上调用Title(网址).但好些会访问不了,原因不明. Function Title(ByVal url As String) As StringOn Error Res ...

  6. VC获取网页标题,解决乱码问题 学习

    博主不让转载 仅记录下地址 稍后 放出自己的代码 http://blog.csdn.net/friendan/article/details/11821135

  7. UIWebView 获取网页标题

    - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *urlString = webView.request.URL.absolu ...

  8. Java访问网络url,获取网页的html代码

    在Java中,Java.net包里面的类是进行网络编程的,其中,java.net.URL类和java.net.URLConection类是编程者方便地利用URL在Internet上进行网络通信.有两种 ...

  9. iOS之UIWebView无法获取web标题

    最近遇到了一个问题,就是在UIWebView的代理方法里,执行document.title的js代码无法获取网页标题,代码如下: - (void)webViewDidFinishLoad:(UIWeb ...

随机推荐

  1. vue 中使用scss

    1.下载 npm install --save-dev sass-loader npm install --save-dev node-sass npm install sass-loader --s ...

  2. Fraction Comparision

    题目链接 题意:输入x,a,y,b求x/a和y/b的大小,范围long long int 思路:因为不想用精度,嫌麻烦,所以用了个巧方法.先求x/a和y/b整形的大小,如果相等,再求(x%a)*b和( ...

  3. (转)VirtualBox下安装CentOS7系统

    转:https://www.cnblogs.com/hihtml5/p/8217062.html 本文假定你已经知道如何安装VirtualBox虚拟机软件,并且已经安装好了. 首先我们需要准备好cen ...

  4. linux nfs文件共享

    ◆一.概念   NFS是网络文件系统(Network File System)的简称,是分布式计算机系统的一个组成部分,可实现在异构网络上共享和装配远程文件系统.   NFS由SUN公司开发,目前已成 ...

  5. openoffice+pdf2swf+FlexPaper在线显示office和pdf

    前提:本人的系统为Ubuntu 13.10 64位系统.本篇是我在配置好环境后一段时间写的,所以操作上可能会有也错误,因此仅供参考. 搜索在线显示office和pdf,最常见的方法就是把都转为swf, ...

  6. JVM调优(四)——tomcat远程debug

    JVM调优(四)--tomcat远程debug tomcat远程debug jdwp协议 使用步骤 登录远程服务器,进入tomcat目录,并打开文件: //tomcat/bin/startup.sh ...

  7. C语言|博客作业12

    一.我学到的内容(整理本课程所学,[用思维导图的方式] 二.我的收获(包括我完成的所有作业的链接+收获)不能只有作业链接,没有收获 作业链接 收获 https://edu.cnblogs.com/ca ...

  8. VC++DLL动态链接库程序

    VC++DLL动态链接库程序 VC++DLL动态链接库程序 C++ DLL 导出函数 使用VS2017等IDE生成dll程序,示例如下: C++ DLL 导出类 1.导出类中第一种方法:简单导出类(不 ...

  9. 安装vue开发环境→安装淘宝镜像的时候报错

    问题: npm WARN deprecated socks@1.1.10: If using 2.x branch, please upgrade to at least 2.1.6 to avoid ...

  10. python上播放mp3歌曲

    我想从python播放我的歌曲(mp3),你能给我一个最简单的命令吗? 这不正确: import wave w = wave.open("e:/LOCAL/Betrayer/Metalik ...