Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse KML file with PHP

Is there a way to parse google maps *.kml file with simple_xml_load_file("*.kml") ?

I need to save in my database name and coordinates of each polygons registered in my KML file. On my PHP script, simple_xml_load_file("*.kml") return false, so I can't read it.

<?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>
        <Schema>
        ...
        </Schema>
        <Style id="FEATURES">
        ...
        </Style>
        <Folder>
            <Placemark>
                <name>
                    name
                </name>
                <Polygon>
                    <LinearRing>
                        <coordinates>
                            coordinates
                        </coordinates>
                    </LinearRing>
                </Polygon>
            </Placemark>
            <Placemark>
                ...
            </Placemark>
        </Folder>
    </Document>
</kml>

I need "name" and "coordinates" values for each "Placemark".

like image 601
jbrtrnd Avatar asked Jan 18 '23 03:01

jbrtrnd


1 Answers

The xml structure is exactly that xml you sent:

For example:

<Document>
<Placemark>
      <name>356HH</name>
      <description>
</description>
      <Polygon><outerBoundaryIs><LinearRing><coordinates>some cordinates here</coordinates></LinearRing></innerBoundaryIs></Polygon>
  <Style><LineStyle><color>ff0000ff</color></LineStyle>  <PolyStyle><fill>0</fill></PolyStyle></Style>
  </Placemark>
  <Placemark>
</document>

And it's my php code:

<?php

$completeurl = "2.xml";
$xml = simplexml_load_file($completeurl);

$placemarks = $xml->Document->Placemark;
$con=mysqli_connect("localhost","root","","j3");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 $query = '';
 $run='';
for ($i = 0; $i < sizeof($placemarks); $i++) {
    $coordinates = $placemarks[$i]->name;
     $cor_d  =  explode(' ', $placemarks[$i]->Polygon->outerBoundaryIs->LinearRing->coordinates);
     $qtmp=array();
     foreach($cor_d as $value){
          $tmp = explode(',',$value);
          $ttmp=$tmp[1];
          $tmp[1]=$tmp[0];
          $tmp[0]=$ttmp; 
          $qtmp[]= '(' . $tmp[0] . ',' .$tmp[1].')';
     }

    $cor_d = json_encode($qtmp);
    $query .='\''.$coordinates.'\', \''.$cor_d.'\'';
    $run .="INSERT INTO jos_rpl_addon_zipinfo (name, boundary) VALUES (".$query." );";

    //echo $run;
    //break;
}
mysqli_query($con,$run);
//echo $run;

mysqli_close($con);
?>
like image 125
Sutechksh Avatar answered Jan 22 '23 02:01

Sutechksh