tags:

views:

23

answers:

1

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  A: 

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;
    }
}
Gordon
Brilliant!! Thank you!! :D
Ashley