我正在解析从Google Map API V3返回的XML。以下是返回的典型XML:
<?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>
这是我用来解析它的PHP代码片段:
$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);
以下是编辑后的输出:
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"
}
}
}
使用$ LatLonBox_result [0] [“north”]看起来很丑陋。这是使用xpath时的情况吗?我期待返回的值可能类似于$ LatLonBox_result [“north”]而没有数组的第一个维度。或者这种做法是错误的? 如果有更好的方法,请赐教。谢谢!
答案 0 :(得分:2)
SimpleXMLElement::xpath
返回始终 数组(事实上你得到它的第一个元素)并找到结果(无论它们只是一个或多个) ),或FALSE
如果有错误。
我认为你的代码很好,除了不是很强大。在使用empty($result)
做任何其他事情之前,最好先用$LatLonBox_result = $xml->xpath('//http:LatLonBox');
if (!empty($LatLonBox_result)) {
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";
}
检查结果。
{{1}}