时时商务社区
标题:
解析file_get_contents模仿浏览器头(user_agent)获取数据
[打印本页]
作者:
bewin83
时间:
2018-2-14 08:16
什么是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,当然你也可以换成其他的。比如中火狐
也可以这样读取:
[U]复制代码[/U] 代码如下:
$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: *//*"
)
);
您可能感兴趣的文章:
深入file_get_contents函数抓取内容失败的原因分析
解析PHP中的file_get_contents获取远程页面乱码的问题
file_get_contents("php://input", "r")实例介绍
php读取本地文件常用函数(fopen与file_get_contents)
PHP file_get_contents设置超时处理方法
php file_get_contents抓取Gzip网页乱码的三种解决方法
解决file_get_contents无法请求https连接的方法
PHP中file_get_contents高級用法实例
php中file_get_contents与curl性能比较分析
php 使用file_get_contents读取大文件的方法
PHP中file_get_contents函数抓取https地址出错的解决方法(两种方法)
欢迎光临 时时商务社区 (http://bbs.4435.cn/)
Powered by Discuz! X3.2