2

我正在解析从 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"] 并且没有数组的第一个维度。或者这种方法是错误的?如果有更好的方法可以做到这一点,请不吝赐教。谢谢!

4

1 回答 1

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";
}
于 2012-10-17T19:41:36.943 回答