0

我需要以下代码的帮助,我需要从 XML 文件中提取 2 个节点,并将它们组合到一个数组中,这是我的代码:

$xml = file_get_contents('myKML.kml');
$dom = new DOMDocument;
$dom->loadXML($xml);
$coordi = $dom->getElementsByTagName('coordinates');

$coords = array();
foreach ($coordi as $coordinates) {
    $args = explode(",", $coordinates->nodeValue);
    $coords[] = array($args[0], $args[1], $args[2]);
}

print_r($coords);

现在我需要添加$place = $dom->getElementsByTagName('name');

所以输出数组应该类似于:

[名称,坐标 1,坐标 2],[名称,坐标 1,坐标 2],[名称,坐标 1,坐标 2]

4

1 回答 1

0

首先使用 Xpath 查询地标,然后获取每个地标的名称和坐标。这是使用来自Wikipedia的示例 KML 的一些来源

$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Placemark>
  <name>New York City</name>
  <description>New York City</description>
  <Point>
    <coordinates>-74.006393,40.714172,0</coordinates>
  </Point>
</Placemark>
</Document>
</kml>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

$result = array();
$places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
foreach ($places as $place) {
  $result = array(
    'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
    'coords' => explode(
      ',', 
      $xpath->evaluate('string(kml:Point/kml:coordinates)', $place, FALSE),
      3
    )
  );
}

var_dump($result);

输出:

array(2) {
  ["name"]=>
  string(13) "New York City"
  ["coords"]=>
  array(3) {
    [0]=>
    string(10) "-74.006393"
    [1]=>
    string(9) "40.714172"
    [2]=>
    string(1) "0"
  }
}
于 2013-11-25T19:59:31.393 回答