php如何将xml对象转换为数组

function simplexml_obj2array($obj) {
    if (count($obj) >= 1) {
        $result = $keys = array();
        foreach ($obj as $key => $value) {
            isset($keys[$key]) ? $keys[$key] += 1 : $keys[$key] = 1;
            if ($keys[$key] == 1) {
                $result[$key] = simplexml_obj2array($value);
            } else if ($keys[$key] == 2) {
                $result[$key] = array($result[$key], simplexml_obj2array($value));
            } else if ($keys[$key] > 2) {
                $result[$key][] = simplexml_obj2array($value);
            }
        }
        return $result;
    } else if (count($obj) == 0) {
        return (string)$obj;
    }
}

echo '<pre>';
print_r(simplexml_obj2array($xml));
echo '</pre>';

使用simplexml_load_file可以很容易得到一个xml对象,但是对于php,人们一般习惯于操作数组,使用上述的函数即可将一个xml对象转换为数组的形式。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注