如何将 XML 对象强制转换为关联数组


how to cast an xml object to a associative array?

我正在使用谷歌 api 进行一些地理编码,想知道如何转换返回的 simplexml 对象?我尝试了以下内容,但它没有强制转换子对象。即..我想要一个多维数组。

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

您可以发出 JSON 请求而不是 XML;建议这样做;除非您的应用程序需要它。然后使用:

json_decode( $result, true );

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

我发现这个函数对于递归地将对象转换为数组非常有用:

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

改编自上面的网站,在课外使用它:

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

SimpleXMLElement对象转换为 json,并将 json 字符串再次解码为关联数组:

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

简单的强制转换为数组并没有更深入,这就是使用通过json_encodejson_decode的技巧的原因。