views:

355

answers:

3

I need to recursively cast a PHP SimpleXMLObject to an array. The problem is that each sub element is also a PHP SimpleXMLElement.

Is this possible?

+1  A: 

Didn't test this one, but this seems to get it done:

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

Taken from http://www.codingforums.com/showthread.php?t=87283

Seb
A: 

It is possible. This is a recursive function which prints out the tags of parent elements and the tags + contents of elements that have no more children. You can alter it to build an array:

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";
}
Petrunov
A: 

I don't see the point since SimpleXMLObject can be threated just like arrays anyway...

But if you really need that, just check chassagnette's answer of in this thread or this post in a forum.

e-satis