从SimpleXML Object到Array的递归转换

问题描述 投票:22回答:5

我需要以递归方式将PHP SimpleXMLObject强制转换为数组。问题是每个子元素也是PHP SimpleXMLElement。

这可能吗?

php casting simplexml
5个回答
63
投票
json_decode(json_encode((array) simplexml_load_string($obj)), 1);

6
投票

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

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


0
投票

有可能的。这是一个递归函数,它打印出父元素的标签和标签+不再有子元素的元素的内容。你可以改变它来构建一个数组:

foreach( $simpleXmlObject as $element )
{
    recurse( $element );
}

function recurse( $parent )
{
    echo '<' . $parent->getName() . '>' . "\n";    

    foreach( $parent->children() as $child )
    {
        if( count( $child->children() ) > 0 )
        {
            recurse( $child );
        }
        else
        {
           echo'<' . $child->getName() . '>';
           echo  iconv( 'UTF-8', 'ISO-8859-1', $child );
           echo '</' . $child->getName() . '>' . "\n";
        }
    }

   echo'</' . $parent->getName() . '>' . "\n";
}

0
投票

我没有看到这一点,因为SimpleXML Object无论如何都可以被视为数组......

但如果你真的需要,请在论坛中查看chassagnette在this threadthis post中的回答。


0
投票

取决于CDATA,阵列等的一些问题(参见:SimpleXMLElement to PHP Array

我想,这将是最好的解决方案:

public function simpleXml2ArrayWithCDATASupport($xml)
{
    $array = (array)$xml;

    if (count($array) === 0) {
        return (string)$xml;
    }

    foreach ($array as $key => $value) {
        if (is_object($value) && strpos(get_class($value), 'SimpleXML') > -1) {
            $array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
        } else if (is_array($value)) {
            $array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
        } else {
            continue;
        }
    }

    return $array;
}
© www.soinside.com 2019 - 2024. All rights reserved.