final class XMLToArray { //public $root_node = 'root'; public static $document; private static $parent = ''; private $array = array(); public function __construct(array $array, $root_node) { self::$document = new DOMDocument('1.0', 'UTF-8'); $root = self::$document->AppendChild( new DOMElement($root_node) ); $this->array = $array; $this->Build($root, $array); } private function Build(DOMElement $node, $arg) { if(is_array($arg)) { foreach($arg as $key=>$val) { if(is_array($val)) { if(is_numeric($key)) { $nn = $node->tagName; if (substr($nn, -1, 1) == 's') { $key = substr($nn, 0, -1); } else { $key = 'UnknownNode'; } } $key = htmlentities($key); $new = $node->AppendChild( new DOMElement($key) ); $this->Build($new, $val); } else { if(is_numeric($key)) { $key = $val; } $key = htmlentities($key); $val = htmlentities($val); try { $node->AppendChild( new DOMElement($key, $val) ); } catch (Exception $ex) { var_dump($ex); } } } } else { $key = 'BlankNode'; $val = htmlentities($val); $node->AppendChild( new DOMElement($key, $val) ); } } public static function Recurse(array $array, $root_node = 'root') { $obj = new XMLToArray($array, $root_node); return XMLToArray::$document; } }