3v4l.org

run code in 300+ PHP versions simultaneously
<?php function xml_to_array($root) { $result = array(); if ($root->hasAttributes()) { $attrs = $root->attributes; foreach ($attrs as $attr) { $result['@attributes'][$attr->name] = $attr->value; } } if ($root->hasChildNodes()) { $children = $root->childNodes; if ($children->length == 1) { $child = $children->item(0); if ($child->nodeType == XML_TEXT_NODE) { $result['_value'] = $child->nodeValue; return count($result) == 1 ? $result['_value'] : $result; } } $groups = array(); foreach ($children as $child) { if (!isset($result[$child->nodeName])) { $result[$child->nodeName] = xml_to_array($child); } else { if (!isset($groups[$child->nodeName])) { $result[$child->nodeName] = array($result[$child->nodeName]); $groups[$child->nodeName] = 1; } $result[$child->nodeName][] = xml_to_array($child); } } } return $result; } $xml = "<Msg> <Txn>submitsms </Txn> <AccountID>123456789</AccountID> <Password>barfoo123</Password> <Message>test message</Message> <RateCode>1</RateCode> <Mobiles> <MobileNo>07123456701</MobileNo> </Mobiles> </Msg>"; $doc = new DOMDocument(); $doc->loadXML($xml); var_dump(xml_to_array($doc));

preferences:
55.81 ms | 402 KiB | 5 Q