且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析xml问题

更新时间:2023-11-24 16:51:58

如果您启用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;
    }
}