0

I am doing some geocoding with the google api and was wondering how do i cast the returned simplexml object? I tried the following but it does no cast the child objects.. ie.. i would like a multi dimensional array.

$url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$adr."
&sensor=false";

$result = simplexml_load_file($url);

$result = (array) $result;
Chris Mccabe
  • 1,902
  • 6
  • 30
  • 61

3 Answers3

1

You could make a JSON request rather than XML; it's recommended; unless your application requires it. Then use:

json_decode( $result, true );

http://us2.php.net/manual/en/function.json-decode.php

JDavis
  • 3,228
  • 2
  • 22
  • 23
0

I found very useful this function for converting Object to Array recursively:

http://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka

Adapted from the site above, to use it outside classes:

function object_to_array($obj) {
        $arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($arrObj as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
                $arr[$key] = $val;
        }
        return $arr;
}
Memochipan
  • 3,405
  • 5
  • 35
  • 60
-1

Turn the SimpleXMLElement object into json and decode the json string again into an associative array:

$array = json_decode(json_encode($result), 1);

The simple cast to array does not go more deep in there, that's why the trick via json_encode and json_decode is used.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • @ChrisMccabe: Not with my PHP version, see as well http://php.net/json_decode - but maybe you have got some PHP that does not have that second parameter of `json_decode` or probably more realistic: some esoteric compile that inverts the seconds parameters meaning ;) – hakre Aug 09 '12 at 00:08