Parsing XML with PHP for Drupal
Thanks to walkah for pointing out the exciting possibilities of Drupal and PHP 5's SimpleXML extension. (And before you ask, yes, we're taking medication to deal with this too-easy excitability issue.)
$q = str_replace(' ', '+', implode(',',$place));
$url = 'http://maps.google.com/maps/geo?q=' . $q . '&output=xml&key=' . variable_get('googlemap_api_key', '');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$c = curl_exec($ch);
curl_close($ch);
$c = new SimpleXMLElement($c);
drupal_set_message('<pre>' . print_r($c, TRUE) . '</pre>');
Raw XML:
<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><Response><name>Espana</name><Status><code>200</code><request>geocode</request></Status><Placemark id="p1"><address>Spain</address><AddressDetails Accuracy="1" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"><Country><CountryNameCode>ES</CountryNameCode></Country></AddressDetails><Point><coordinates>-3.749220,40.463667,0</coordinates></Point></Placemark></Response></kml>
PHP objectified XML:
SimpleXMLElement Object
(
[Response] => SimpleXMLElement Object
(
[name] => Espana
[Status] => SimpleXMLElement Object
(
[code] => 200
[request] => geocode
)[Placemark] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => p1
)[address] => Spain
[AddressDetails] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Accuracy] => 1
)[Country] => SimpleXMLElement Object
(
[CountryNameCode] => ES
))
[Point] => SimpleXMLElement Object
(
[coordinates] => -3.749220,40.463667,0
))
)
)
As you can see it's the same structure of data Agaric didn't like when provided as JSON, except even worse, as the coordinates would still need to be parsed.
We'll try JSON for this but it's nice to know that PHP5 has easy ways to turn XML as well as JSON structured data into objects we programmers understand.
Comments
Post new comment