PHP file_get_contents()的行为与浏览器不同 [英] PHP file_get_contents() behaves differently to browser

查看:137
本文介绍了PHP file_get_contents()的行为与浏览器不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP下载网页的内容. 当我发出命令时:

I'm trying to download the contents of a web page using PHP. When I issue the command:

$f = file_get_contents("http://mobile.mybustracker.co.uk/mobile.php?searchMode=2");

它返回一个页面,报告服务器已关闭.但是,当我将相同的URL粘贴到浏览器中时,我得到了预期的页面.

It returns a page that reports that the server is down. Yet when I paste the same URL into my browser I get the expected page.

有人知道这是什么原因吗?是否有file_get_contents传输任何将其与浏览器请求区分开的标头?

Does anyone have any idea what's causing this? Does file_get_contents transmit any headers that differentiate it from a browser request?

推荐答案

是的,有区别-浏览器倾向于发送大量附加内容

Yes, there are differences -- the browser tends to send plenty of additionnal HTTP headers, I'd say ; and the ones that are sent by both probably don't have the same value.

在这里,经过几次测试后,似乎有必要传递名为Accept的HTTP标头.

Here, after doing a couple of tests, it seems that passing the HTTP header called Accept is necessary.

这可以使用file_get_contents的第三个参数来完成,以指定其他上下文信息:

This can be done using the third parameter of file_get_contents, to specify additionnal context informations :

$opts = array('http' =>
    array(
        'method'  => 'GET',
        //'user_agent '  => "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2) Gecko/20100301 Ubuntu/9.10 (karmic) Firefox/3.6",
        'header' => array(
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*\/*;q=0.8
'
        ), 
    )
);
$context  = stream_context_create($opts);

$f = file_get_contents("http://mobile.mybustracker.co.uk/mobile.php?searchMode=2", false, $context);
echo $f;

有了这个,我就能获得页面的HTML代码.

With this, I'm able to get the HTML code of the page.


注意:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆