3v4l.org

run code in 300+ PHP versions simultaneously
<?php $xml = '<person> <child role="son1"> <child role="daughter1"/> </child> <child role="daughter2"> <child role="son2"> <child role="son3"/> </child> </child> </person>'; function xml2assoc($obj, &$arr) { $children = $obj->children(); foreach ( $children as $elementName => $node ) { if (!isset($arr[$elementName])) { $arr[$elementName] = array(); } $temp = array(); $attributes = $node->attributes(); foreach ( $attributes as $attributeName => $attributeValue ) { $attribName = strtolower(trim((string) $attributeName)); $attribVal = trim((string) $attributeValue); $temp[$attribName] = $attribVal; } $text = (string) $node; $text = trim($text); if (strlen($text) > 0) { $temp ['text='] = $text; } $arr[$elementName][] = $temp; $nextIdx = count($arr[$elementName]); xml2assoc($node, $arr[$elementName][$nextIdx - 1]); } return; } $dom = new SimpleXMLElement($xml); $arr = array(); xml2assoc($dom, $arr); print_r($arr);

preferences:
32.76 ms | 406 KiB | 5 Q