简体   繁体   中英

SimpleXML returns empty arrays

I'm trying to get the latitude and longitude of a city with the Google Maps API and through PHP (SimpleXML).

I try to do it like this:

$xml = simplexml_load_file("http://maps.googleapis.com/maps/api/geocode/xml?address=Brussels,Belgium&sensor=false");
$lat= $xml->xpath("lat");
print_r($lat);

But this returns an empty array every time. Am I missing something?

Any help is much appreciated.

To search for a particular lat do this:

<?php
  $xml = simplexml_load_file("http://maps.googleapis.com/maps/api/geocode/xml?address=Brussels,Belgium&sensor=false");
  $lat= $xml->xpath("/GeocodeResponse/result/geometry/location/lat");
  print_r($lat);
?>

For all lat occurrences specify the path of //lat .

You should use this instead:

$xml->xpath("//lat");

In this way you're searching for lat tag which could be everywhere in the tree.

Your XPath query is wrong. It should be:

$lat= $xml->xpath("//lat");

The // tells xPath to search for lat nodes no matter where they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM