dongwu4834 2010-08-19 14:53
浏览 56

解析xml问题

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

Where am I going wrong? Thanks

$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 />";
       }
     }
   }
}
  • 写回答

1条回答 默认 最新

  • doudula1974 2010-08-19 14:57
    关注

    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) {
    

    when it should be

    foreach($results->Location as $location) {
    

    Same for the other elements.
    Also, it's not $area->area but just $area.

    Full fixed code:

    $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 />";
           }
         }
       }
    }
    

    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/>";
    }
    

    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;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题