3

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.

samn
  • 2,699
  • 4
  • 20
  • 24

3 Answers3

4

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Mikhail
  • 8,692
  • 8
  • 56
  • 82
2

You should use this instead:

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

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

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
1

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337