解析xml问题 [英] Parsing xml problem
问题描述
我正在尝试使用PHP和simplexml_load_file对此进行解析,但未显示任何内容?
I'm trying to parse this using PHP and simplexml_load_file but its not showing anything?
http://developer.multimap.com /API/geocode/1.2/OA10081917657704697?qs=Heaton&CountryCode=GB
我要去哪里错了?谢谢
$results = simplexml_load_file($url);
foreach($results->Location() as $location) {
foreach($location->Address() as $address) {
foreach($address->Areas() as $areas) {
foreach($areas->Area as $area) {
echo $area->area;
echo "<br />";
}
}
}
}
推荐答案
如果您启用display_errors
,您会看到有一个
If you had error_reporting
and display_errors
enabled, you would see there is a
Fatal error: Call to undefined method SimpleXMLElement::Location()
您正在尝试通过方法调用来访问元素,例如
You are trying to access the elements with Method calls, e.g.
foreach($results->Location() as $location) {
应该在什么时候
foreach($results->Location as $location) {
其他元素相同.
另外,它不是$area->area
而是$area
.
Same for the other elements.
Also, it's not $area->area
but just $area
.
完整的固定代码:
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
foreach($location->Address as $address) {
foreach($address->Areas as $areas) {
foreach($areas->Area as $area) {
echo $area;
echo "<br />";
}
}
}
}
在旁注中,使用XPath时,您可以获取文档中的所有Area元素,而不会像疯狂一样循环.但是,由于元素是命名空间,因此必须先使用前缀注册该命名空间才能使用XPath:
On a sidenote, you can get all Area elements in the document without looping like crazy when using an XPath. However, since the elements are namespaced, you have to register that namespace with a prefix first to be able to use XPath:
$results = simplexml_load_file($url);
$results->registerXPathNamespace('d', 'http://clients.multimap.com/API');
$areas = $results->xpath('//d:Area');
foreach($areas as $area) {
echo "$area<br/>";
}
另一种克服所有元素(尽管比使用XPath的性能低)的方法是使用Iterator遍历DOM树:
Yet another way to get over all elements (though less performat than using an XPath) would be to use an Iterator to walk over the DOM Tree:
$elements = new RecursiveIteratorIterator(
simplexml_load_file($url, 'SimpleXmlIterator'));
foreach($elements as $element) {
if($element->getName() === 'Area') {
echo $element;
}
}
这篇关于解析xml问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!