我必须从 URL 读取 XML 文件
$map_url = "http://maps.google.com/maps/api/directions/xml?origin=".$merchant_address_url."&destination=".$customer_address_url."&sensor=false";
这样我就得到了一个类似的 URL:
我正在使用该函数读取数据:
$response_xml_data = file_get_contents($map_url);
if($response_xml_data){
echo "read";
}
$data = simplexml_load_string($response_xml_data);
echo "<pre>"; print_r($data); exit;
但没有成功,有什么帮助吗?
您可以使用 "simplexml_load_file" 函数从 XML 获取数据。请参考此链接
http://php.net/manual/en/function.simplexml-load-file.php
$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);
您的代码似乎是正确的,请检查是否启用了 fopen wrappers 功能(php.ini 中的 allow_url_fopen = On
)
此外,如其他答案所述,您应该提供正确编码的 URI 或使用 urlencode() 函数对其进行编码。您还应检查获取 XML 字符串是否有任何错误,以及是否有任何解析错误,您可以使用 libxml_get_errors() 输出错误信息,如下所示:
<?php
if (($response_xml_data = file_get_contents($map_url))===false){
echo "Error fetching XML\n";
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
echo "Error loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
} else {
print_r($data);
}
}
?>
如果出现无法获取 XML 代码的问题,可能是因为您需要在请求中包含一些自定义标头,请查看如何使用 stream_context_create() 创建自定义流上下文,以便在调用示例 4 中的 file_get_contents()
时使用,网址为 http://php.net/manual/en/function.file-get-contents.php。