How to convert array to SimpleXML

前端 未结 30 2657
遇见更好的自我
遇见更好的自我 2020-11-21 06:52

How can I convert an array to a SimpleXML object in PHP?

30条回答
  •  一个人的身影
    2020-11-21 07:34

    function toXML($data, $obj = false, $dom) {
        $is_first_level = false;
        if($obj === false) {
            $dom = new DomDocument('1.0');
            $obj = $dom;
            $is_first_level = true;
        }
    
        if(is_array($data)) {
            foreach($data as $key => $item) {
                $this->toXML($item, $obj->appendChild($dom->createElement($key)), $dom);
            }
        }else {
            $obj->appendChild($dom->createTextNode($data));
        }
    
        if($is_first_level) {
            $obj->formatOutput = true;
            return $obj->saveXML();
        }
        return $obj;
    }
    

提交回复
热议问题