Parsing KML files with PHP

For my current project at MsF, I need to process Google’s geoinformation data scheme KML with PHP. As the format is XML based, open and clearly defined, its actually pretty simple. The following code uses the Document Object Model in order to retrieve all <Point> nodes from a <Placemark>, which contain the string of coordinates as their element content.

<code>

function parseKML(){

// Create a new DOM model
$doc = new DOMDocument();
// Load a KML file
$doc->load( ‘example.kml’ );
//Pick all Point – Elements
$points = $doc->getElementsByTagName( “Point” );
// For every point, extract the coordinates
foreach( $points as $point ){
$coordinates = $point->getElementsByTagName( “coordinates” );
$coordinate = $coordinates->item(0)->nodeValue;
$geoPoint = parseCoord($coordinate);

}

</code>

The following function applies a regular expression to the given string of coordinates. This regex filters the longitude and the latitude of a given set of coodinates and creates a new GeoPoint, which is simply a class called GeoPoint, having the two parameters as member variables.

<code>

function parseCoord($coordinate){
$geopoint = null;
// Delete all blanks
$coordinate = str_replace(” “, “”, $coordinate);
//Regular expression
$regex = “/([-+]{0,1}[0-9]{1,}\.{1}[0-9]{1,})\,([-+]{0,1}[0-9]{1,}\.{1}[0-9]{1,})/”;
// Apply regex
try {

$match = preg_match($regex, $coordinate,$result);

// If the string is valid, retrieve results
if($match>0){
$long = $result[1];
$lat = $result[2];
$geopoint = new GeoPoint($long, $lat);
}
} catch (Exception $e) {
echo ‘There was an error: ‘,  $e->getMessage(), “\n”;
}
return $geopoint;
}

</code>

Please excuse the poor code formatting. My theme does not yet support any of the code highlighting plugins.

One thought on “Parsing KML files with PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.