我试图从我的PHP脚本中下载的文件就是这个:
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.
知道怎么做吗?
非常感谢,巴勃罗。
更新以添加代码:
$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:
$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);
答案 0 :(得分:5)
您不需要cURL
,也不需要file_get_contents
将XML加载到任何PHP's DOM Based XML parsers中。
但是,在您的特定情况下,问题似乎是服务器需要http请求中的用户代理。如果未在php.ini中设置用户代理,则可以使用libxml functions并将其作为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
。您可以将流上下文作为第三个参数传递:
echo file_get_contents(
'http://www.navarra.es/apps…/Farmacias.xml',
FALSE,
stream_context_create(
array(
'http' => array(
'user_agent' => 'php'
)
)
)
);
答案 1 :(得分:0)
我一直在使用为@Gordon提供的解决方案,它在localhost中完美运行:
$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);
但是当我将所有文件上传到服务器时......一如既往的惊喜。我开始收到错误在中的服务器配置中禁用了URL文件访问权限,因此我更改了此代码的所有file_get_contents()
,我找到了here:
function get_content($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Googlebot/2.1...");
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
你认为这是一个好方法吗?
谢谢,巴勃罗。