0
votes

I am parsing a google map api for getting latlong form address.I got the xml succesfully.How can i get the latlong from the xml response.

My response is

SimpleXMLElement Object ( [status] => OK [result] => SimpleXMLElement Object ( [type] => Array ( [0] => locality [1] => political )[formatted_address] => New Delhi, Delhi, India [address_component] => Array ( [0] => SimpleXMLElement Object ( [long_name] => New Delhi [short_name] => New Delhi [type] => Array ( [0] => locality [1] => political ) )[1] => SimpleXMLElement Object ( [long_name] => West Delhi [short_name] => West Delhi [type] => Array ( [0] => administrative_area_level_2 [1] => political )) [2] => SimpleXMLElement Object ( [long_name] => Delhi [short_name] => DL [type] => Array ( [0] => administrative_area_level_1 [1] => political ) ) [3] => SimpleXMLElement Object ( [long_name] => India [short_name] => IN [type] => Array ( [0] => country [1] => political ) ) )[geometry] => SimpleXMLElement Object ( [location] => SimpleXMLElement Object ( [lat] => 28.6353080 [lng] => 77.2249600 ) [location_type] => APPROXIMATE [viewport] => SimpleXMLElement Object ( [southwest] => SimpleXMLElement Object ( [lat] => 28.4010669 [lng] => 76.8396999 ) [northeast] => SimpleXMLElement Object ( [lat] => 28.8898159 [lng] => 77.3418146 ) ) [bounds] => SimpleXMLElement Object ( [southwest] => SimpleXMLElement Object ( [lat] => 28.4010669 [lng] => 76.8396999 ) [northeast] => SimpleXMLElement Object ( [lat] => 28.8898159 [lng] => 77.3418146 ) ) ) ) )

i want to get the geometry->location->lat value

Help me out from this issue

thanks in advance

1

1 Answers

2
votes

It is easier with DOM+XPath, the DOMXpath::evaluate() method can fetch scalar values out of an xml:

$xml = <<<'XML'
<GeocodeResponse>
 <status>OK</status>
 <result>
  <geometry>
   <location>
    <lat>37.4217550</lat>
    <lng>-122.0846330</lng>
   </location>
   <location_type>ROOFTOP</location_type>
   <viewport>
    <southwest>
     <lat>37.4188514</lat>
     <lng>-122.0874526</lng>
    </southwest>
    <northeast>
     <lat>37.4251466</lat>
     <lng>-122.0811574</lng>
    </northeast>
   </viewport>
  </geometry>
 </result>
</GeocodeResponse>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$lat = $xpath->evaluate('number(/GeocodeResponse/result/geometry/location/lat)');
$lng = $xpath->evaluate('number(/GeocodeResponse/result/geometry/location/lng)');

var_dump($lat, $lng);

Output:

float(37.421755)
float(-122.084633)