Zeratops Zeratops - 8 days ago 4x
PHP Question

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

I have a .kml file shaped like this :

<?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">
<Style id="style1">
<Folder id="layer 0">
-2.94040373,54.83409343483 -2.943834733,54.893839393


How can I get this file as a
, and get ALL tag element with name "coordinates" ?

The goal is to be able to get the coordinates, even if the file shape change, like for example :

<kml xmlns="http://earth.google.com/kml/2.0">
<name>OpenLayers export</name>
<description>No description available</description>
<description>No description available</description>
-2.94040373,54.83409343483 -2.943834733,54.893839393

My attempts was to loop through the document using
but unfortunately I would not be reliable as the "tag order" change between those 2 documents, and I do not know why it does not follow a single pattern (which lead me to ask this question because it may have more than 2 shape for a KML ? correct me if I am wrong).


Use DOMDocument class to parse XML. Then use getElementsByTagName() to get all coordinates elements.

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