Parsing KML files with PHP

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 nodes from a , which contain the string of coordinates as their element content.

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);

}

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.


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;  
}