如何使用 php DOMDocument 获取 KML 文件中的特定标签?

How to get specific tag in KML file using php DOMDocument?

我有一个 .kml 文件,形状如下:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>myFile.shp</name>
    <Style id="style1">
        <PolyStyle>
            <color>ff00ff00</color>
        </PolyStyle>
    </Style>
    <Folder id="layer 0">
        <name>background</name>
        <Placemark>
            <styleUrl>#style1</styleUrl>
            <LineString>
                <coordinates>
                    -2.94040373,54.83409343483 -2.943834733,54.893839393
                </coordinates>
            </LineString>
        </Placemark>
      </Folder>
</Document>
</kml>

问题

如何将此文件作为 DOMDocument 获取,并获取名称为 [=31= 的 ALL 标签元素] ?

目标是能够获取坐标,即使文件形状发生变化,例如:

<kml xmlns="http://earth.google.com/kml/2.0">
  <Folder>
    <name>OpenLayers export</name>
    <description>No description available</description>
    <Placemark>
      <name>OpenLayers.Feature.Vector_7341</name>
      <description>No description available</description>
      <Polygon>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>
              -2.94040373,54.83409343483 -2.943834733,54.893839393
            </coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
  </Folder>
</kml>

我的尝试是使用 simplexml_load_file() 遍历文档,但不幸的是,我不可靠,因为这两个文档之间的 "tag order" 发生了变化,而且我不知道为什么它不遵循单一模式(这导致我问这个问题,因为它可能有超过 2 个 KML 形状?如果我错了请纠正我)。

使用DOMDocument class to parse XML. Then use getElementsByTagName()获取所有coordinates个元素。

$dom = new DOMDocument();
// load file 
$dom->load("file.kml");
// get coordinates tag
$coordinates = $dom->getElementsByTagName("coordinates");
foreach($coordinates as $coordinate){
    echo $coordinate->nodeValue;
}