Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive cast from SimpleXMLObject to Array

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?

like image 254
Glen Solsberry Avatar asked May 07 '09 14:05

Glen Solsberry


2 Answers

json_decode(json_encode((array) simplexml_load_string($obj)), 1);
like image 196
Ajayi Oluwaseun Emmanuel Avatar answered Oct 17 '22 03:10

Ajayi Oluwaseun Emmanuel


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

like image 6
Seb Avatar answered Oct 17 '22 03:10

Seb