Thursday 4 June 2020

How to convert a multidimensional Array To XML in PHP

function createxmlele($data, $name='root', &$doc=null, &$node=null){
        if ($doc==null){
            $doc = new DOMDocument('1.0','UTF-8');
            $doc->formatOutput = TRUE;
            $node = $doc;
        }

        if (is_array($data)){
            foreach($data as $var=>$val){
                if (is_numeric($var)){
                    $this->createxmlele($val, $name, $doc, $node);
                }else{
                    if (!isset($child)){
                        $child = $doc->createElement($name);
                        $node->appendChild($child);
                    }

                    $this->createxmlele($val, $var, $doc, $child);
                }
            }
        }else{
            $child = $doc->createElement($name);
            $node->appendChild($child);
            $textNode = $doc->createTextNode($data);
            $child->appendChild($textNode);
        }

        if ($doc==$node){
            return $doc;
        }
    }