How to convert array to SimpleXML

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

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

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 07:26

    Here is my entry, simple and clean..

    function array2xml($array, $xml = false){
        if($xml === false){
            $xml = new SimpleXMLElement('');
        }
        foreach($array as $key => $value){
            if(is_array($value)){
                array2xml($value, $xml->addChild($key));
            }else{
                $xml->addChild($key, $value);
            }
        }
        return $xml->asXML();
    }
    
    
    header('Content-type: text/xml');
    print array2xml($array);
    

提交回复
热议问题