从 SimpleXMLObject 到 Array 的递归转换

2022-08-30 16:19:34

我需要递归地将PHP SimpleXMLObject转换为数组。问题是每个子元素也是一个PHP SimpleXMLElement。

这可能吗?


答案 1
json_decode(json_encode((array) simplexml_load_string($obj)), 1);

答案 2

没有测试这个,但这似乎完成了它:

function convertXmlObjToArr($obj, &$arr) 
{ 
    $children = $obj->children(); 
    foreach ($children as $elementName => $node) 
    { 
        $nextIdx = count($arr); 
        $arr[$nextIdx] = array(); 
        $arr[$nextIdx]['@name'] = strtolower((string)$elementName); 
        $arr[$nextIdx]['@attributes'] = array(); 
        $attributes = $node->attributes(); 
        foreach ($attributes as $attributeName => $attributeValue) 
        { 
            $attribName = strtolower(trim((string)$attributeName)); 
            $attribVal = trim((string)$attributeValue); 
            $arr[$nextIdx]['@attributes'][$attribName] = $attribVal; 
        } 
        $text = (string)$node; 
        $text = trim($text); 
        if (strlen($text) > 0) 
        { 
            $arr[$nextIdx]['@text'] = $text; 
        } 
        $arr[$nextIdx]['@children'] = array(); 
        convertXmlObjToArr($node, $arr[$nextIdx]['@children']); 
    } 
    return; 
} 

摘自 http://www.codingforums.com/showthread.php?t=87283


推荐