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;
3
  • Notice: Undefined variable: adr; Notice: Undefined variable: result Commented Aug 7, 2012 at 22:46
  • well done.. its for context of the code Commented Aug 7, 2012 at 22:47
  • Possible duplicate of stackoverflow.com/questions/99350/… Commented Aug 7, 2012 at 22:52

3 Answers 3

1

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

json_decode( $result, true );

https://www.php.net/manual/en/function.json-decode.php

Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

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

1 Comment

@ChrisMccabe: Not with my PHP version, see as well 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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.