如何使用PHP以一种奇怪的方式重定向XML文件?

Pui*_*ber 3 php xml curl file-get-contents

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

http://www.navarra.es/appsext/DescargarFichero/default.aspx?codigoAcceso=OpenData&fichero=Farmacias/Farmacias.xml 
Run Code Online (Sandbox Code Playgroud)

但我不能既不使用file_get_contents()也不使用cURL.我收到了错误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);
}
Run Code Online (Sandbox Code Playgroud)

而且该解决方案由于@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);
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 5

您不需要cURL,也不需要file_get_contents将XML加载到PHP的任何基于DOM的XML解析器中.

但是,在您的特定情况下,问题似乎是服务器期望http请求中的用户代理.如果未在php.ini中设置用户代理,则可以使用libxml函数并将其作为流上下文提供:

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();
Run Code Online (Sandbox Code Playgroud)

现场演示

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

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

现场演示