我如何使用PHP下载一个XML文件重定向以一些奇怪的方式? [英] How can I download using PHP a XML file redirected in some weird way?
问题描述
我要从我的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
。我得到错误对象引用未设置为对象的实例。
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.
任何想法如何做它?
非常感谢Pablo。
更新后添加了代码:
$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: / p>
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);
推荐答案
您不需要 cURL
,也不要 file_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屋!