User login

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

http://us3.php.net/simplexml

  $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.

Resolution

Searched words: 
xml with aid XML KML Google geocode map coordinates country code

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.