我有一个像这样的.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
获取,并获取名称为“coordinates”的 所有 标记元素?
目标是能够获取坐标,即使文件形状发生变化,例如:
<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()
遍历文档,但遗憾的是,由于“标记顺序”在这两个文档之间发生了变化,我不会可靠,我不知道它为什么不遵循单一模式(这导致我问这个问题,因为它可能有超过2个形状的KML?如果我错了,请纠正我。)
答案 0 :(得分:1)
使用DOMDocument
类来解析XML。然后使用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;
}