Skip to content

Instantly share code, notes, and snippets.

@mstenta
Forked from woodbri/parse-kml.php
Last active February 8, 2024 07:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstenta/78721add8c3a08c8b79afdd0e2640469 to your computer and use it in GitHub Desktop.
Save mstenta/78721add8c3a08c8b79afdd0e2640469 to your computer and use it in GitHub Desktop.
Script to parse a kml file
<?php
// Enter the name of the KML file here.
$kml_filename = '';
$xml = simplexml_load_file($kml_filename);
$folders = $xml->Document->Folder;
foreach ($folders as $folder) {
print "Name: " . $folder->name . "\n";
print "Description: " . $folder->description . "\n";
$children = $folder->children();
foreach ($children as $child) {
print ' Name: ' . $child->name . "\n";
print ' Description: ' . $child->description . "\n";
$type = 'NONE';
$coordinates = '';
$geom = NULL;
if (isset($child->Point)) {
$type = 'POINT';
$coordinates = $child->Point->coordinates;
$geom = preg_split('/\s+/', trim($coordinates));
}
elseif (isset($child->LineString)) {
$type = 'LINESTRING';
$coordinates = $child->LineString->coordinates;
$geom = preg_split('/\s+/', trim($coordinates));
if (count($geom) and $geom[0] == $geom[count($geom)-1]) {
$type = 'POLYGON';
}
}
elseif (isset($child->Polygon)) {
$type = 'POLYGON';
$coordinates = $child->Polygon->outerBoundaryIs->LinearRing->coordinates;
$geom = preg_split('/\s+/', trim($coordinates));
}
$coords = array();
foreach ($geom as $g) {
$tmp = explode(',', $g);
$coords[] = "$tmp[0] $tmp[1]";
}
if ($type == 'POLYGON') {
$wkt = $type . '((' . implode(',', $coords) . '))';
}
else {
$wkt = $type . '(' . implode(',', $coords) . ')';
}
print ' ' . $wkt . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment