KML PHP Class
July 28th, 2006I’ve been doing a lot of work with Google Earth and custom KML implementations lately, so I thought I would take some time and streamline the process in PHP. I put together a PHP5 class that cleans up the creation process of KML by using objects. The two biggest time savers for this method are more concise and legable code by not mixing PHP, and my personal favorite, no need to worry about KML formatting. Everything is passed through libtidy in the end, so it all looks nicely formatted as Google Earth is pretty picky about that.
The class also contains a compression feature for creating kmz files. It uses a simple zip library that I found in the code for phpmyadmin. Both files can be found here.
Direct knowledge of KML however is still very much required. When working with this class I reference the KML docs online at http://earth.google.com/kml/kml_tags_21.html.
A word of caution about the consistency of KML, there are several inconsistencies in KML and those are not accouted for in this script.
As with most code, it’s better by example. This is a short example for creating a basic KML document. I added a few objects to show how the class works, but keep in mind this isn’t a complete example.
# start a new document
$kml_file = new KML(’File’);# Create a Document object
$document = new KML(’Document’);
$document->name = “Document Name”;
$document->description = “Document Description”;# create an object in this case a style
$style = new KML(’Style’);
$style->id = “radio”;# create a list style
$liststyle = new KML(’ListStyle’);
$liststyle->listItemType = “radioFolder”;# add the ListStyle object to the Style object
$style->addObject($liststyle);# add the Style object to the Document object
$document->addObject($style);# add the Document object to the KML object
$kml_file->addObject($document);# output the results
$kml_file->output_kml();
OR
# output the results with zip compression
$kml_file->output_kmz();