我有一个。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
,并获得ALL标记元素,名称为"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 ?如果我说错了请指正)。
使用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;
}