如何使用 PHP 下载以某种奇怪方式重定向的 XML 文件? [英] How can I download using PHP a XML file redirected in some weird way?

查看:30
本文介绍了如何使用 PHP 下载以某种奇怪方式重定向的 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的 PHP 脚本下载的文件是这个:

The file which I'm trying to download from my PHP script is this one:

http://www.navarra.es/appsext/DescargarFichero/default.aspx?codigoAcceso=OpenData&fichero=Farmacias/Farmacias.xml 

但我既不能使用 file_get_contents() 也不能使用 cURL.我收到错误 Object reference not set to an instance of an object.

But I can't do it using neither file_get_contents() nor cURL. I'm getting the error Object reference not set to an instance of an object.

知道怎么做吗?

非常感谢,巴勃罗.

更新以添加代码:

$url = "http://www.navarra.es/appsext/DescargarFichero/default.aspx?codigoAcceso=OpenData&fichero=Farmacias/Farmacias.xml";
$simple = simplexml_load_file(file_get_contents($url));
foreach ($simple->farmacia as $farmacia)
{
    var_dump($farmacia);
}

以及解决方案感谢@Gordon:

And the solution thanks to @Gordon:

$url = "http://www.navarra.es/appsext/DescargarFichero/default.aspx?codigoAcceso=OpenData&fichero=Farmacias/Farmacias.xml";
$file = file_get_contents($url, FALSE, stream_context_create(array('http' => array('user_agent' => 'php' ))));
$simple = simplexml_load_string($file);

推荐答案

您不需要 cURLfile_get_contents 将 XML 加载到任何 PHP 的基于 DOM 的 XML 解析器.

You dont need cURL, nor file_get_contents to load XML into any of PHP's DOM Based XML parsers.

但是,在您的特定情况下,问题似乎是服务器需要 http 请求中的用户代理.如果您的 php.ini 中没有设置用户代理,您可以使用 libxml函数 并将其作为流上下文一个>:

However, in your particular case, the issue seems to be that the server expects a user agent in the http request. If the user agent is not set in your php.ini, you can use the libxml functions and provide it as a stream context:

libxml_set_streams_context(
    stream_context_create(
        array(
            'http' => array(
                'user_agent' => 'php'            
            )
        )
    )
);

$dom = new DOMDocument;
$dom->load('http://www.navarra.es/app…/Farmacias.xml');
echo $dom->saveXml();

现场演示

如果以后不想解析 XML 文件,也可以使用 file_get_contents.您可以将流上下文作为第三个参数传递:

If you dont want to parse the XML file afterwards, you can use file_get_contents as well. You can pass the stream context as the third argument:

echo file_get_contents(
    'http://www.navarra.es/apps…/Farmacias.xml',
    FALSE,
    stream_context_create(
        array(
            'http' => array(
                'user_agent' => 'php'            
            )
        )
    )
);

现场演示

这篇关于如何使用 PHP 下载以某种奇怪方式重定向的 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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