Heim  >  Artikel  >  php教程  >  解析file_get_contents模仿浏览器头(user_agent)获取数据

解析file_get_contents模仿浏览器头(user_agent)获取数据

WBOY
WBOYOriginal
2016-06-13 11:45:11937Durchsuche

什么是user agent
User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。
网站可以通过判断不同UA来呈现不同的网站,例如手机访问和PC访问显示不同的页面。
PHP在用file_get_contents函数采集网站时,有时会明明用浏览器可以看,但就是采不到任何内容。
这很有可能是服务器上做了设置,根据 User_agent判断是否为正常的浏览器请求,因为默认PHP的file_get_contents函数是不发送ua的。
如果要采集这样的网站,我们就必须要让PHP模拟浏览器发送UA,欺骗网站返回正常内容。

实现如下:
ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 4399Box.560; .NET4.0C; .NET4.0E)');
这是模拟IE8环境下的UA,当然你也可以换成其他的。比如中火狐
也可以这样读取:

复制代码 代码如下:


$opts = array(
'http'=>array(
    'method'=>"GET",
    'header'=>"Host: zh.wikipedia.org\r\n" .
              "Accept-language: zh-cn\r\n" .
              "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 4399Box.560; .NET4.0C; .NET4.0E)" .
              "Accept: *//*"
)
);

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn