我需要以下代码的帮助, 我需要从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');
所以输出数组应该类似于:
[name,coordinate1,coordinate2],[name,coordinate1,coordinate2],[name,coordinate1,coordinate2]
答案 0 :(得分: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"
}
}