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 />";
       }
     }
   }
}
2
  • Right after the simplexml_load_file call, put in var_dump($results) and show what's returned. Also, have you checked your logs? And set error_reporting to E_ALL to check for errors... Commented Aug 19, 2010 at 14:57
  • $xml = simplexml_load_file($url); var_dump($xml); That dumps everything back Commented Aug 19, 2010 at 15:01

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.