I am parsing the XML returned from Google Map API V3. Here is the typical XML returned:
<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="http://earth.google.com/kml/2.0"><Response>
<name>40.74445606,-73.97495072</name>
<Status>
<code>200</code>
<request>geocode</request>
</Status>
<Placemark id="p1">
<address>317 E 34th St, New York, NY 10016, USA</address>
<AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"><Country><CountryNameCode>US</CountryNameCode><CountryName>USA</CountryName><AdministrativeArea><AdministrativeAreaName>NY</AdministrativeAreaName><Locality><LocalityName>New York</LocalityName><Thoroughfare><ThoroughfareName>317 E 34th St</ThoroughfareName></Thoroughfare><PostalCode><PostalCodeNumber>10016</PostalCodeNumber></PostalCode></Locality></AdministrativeArea></Country></AddressDetails>
<ExtendedData>
<LatLonBox north="40.7458050" south="40.7431070" east="-73.9736017" west="-73.9762997" />
</ExtendedData>
<Point><coordinates>-73.9749507,40.7444560,0</coordinates></Point>
</Placemark>
</Response></kml>
Here is a fragment of the PHP code I’m using to parse it:
$xml = new SimpleXMLElement($url, null, true);
$xml->registerXPathNamespace('http', 'http://earth.google.com/kml/2.0');
$LatLonBox_result = $xml->xpath('//http:LatLonBox');
echo "North: " . $LatLonBox_result[0]["north"] . "\n";
echo "South: " . $LatLonBox_result[0]["south"] . "\n";
echo "East: " . $LatLonBox_result[0]["east"] . "\n";
echo "West: " . $LatLonBox_result[0]["west"] . "\n";
var_dump($LatLonBox_result);
Here is the edited output:
North: 40.7458050
South: 40.7431070
East: -73.9736017
West: -73.9762997
array(1) {
[0]=>
object(SimpleXMLElement)#10 (1) {
["@attributes"]=>
array(4) {
["north"]=>
string(10) "40.7458050"
["south"]=>
string(10) "40.7431070"
["east"]=>
string(11) "-73.9736017"
["west"]=>
string(11) "-73.9762997"
}
}
}
Using $LatLonBox_result[0][“north”] seems ugly looking to me. Is this just how things are when working with xpath? I was expecting a returned value perhaps something like $LatLonBox_result[“north”] and not have the first dimension of the array. Or is this approach wrong?
If there is a better way to do this, please kindly enlighten me. Thanks!
SimpleXMLElement::xpathreturns always an array (in fact you are getting the first element of it) with the results found (regardless they are only one or more), orFALSEin case of error.I think your code is just fine, except for being not very robust. You better check the result with
empty($result)before doing anything else with it.