středa 30. dubna 2008

Parsing KML in php

I've tried to write a script, that would translate an street address to GPS location. Google maps has quite nice API, which can do this.

The request looks like this:

http://maps.google.com/maps/geo?q=vsehrdova+6,+praha,+czech+republic&output=xml&key=abcdefg


Response is returned in google standard kml.

php code:

$url= 'http://maps.google.com/maps/geo?q='.$q.'&output=xml&key='.$key;
$dom = new DomDocument();
$dom->loadHTMLFile($url);
$sxe = simplexml_import_dom($dom);

$xml = $this->simxml2array($sxe);

It is possible to use SimpleXmlElement, but I like more php arrays, so I used this function to convert SimpleXmlElement to php array.



function simxml2array($object){
$return=NULL;

if(is_array($object)){
foreach($object as $key => $value){
$key=strtolower($key);
$return[$key]=$this->simxml2array($value)
}
}else{
$var=get_object_vars($object);

if($var){
foreach($var as $key => $value){
$key=strtolower($key);
$return[$key]=$this->simxml2array($value);
}
}else
return strval($object); // strval and everything is fine
}

return $return;
} //simxml2array

Žádné komentáře: