How to convert array to SimpleXML

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

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

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:08

    Here's a function that did the trick for me:

    Just call it with something like

    echo arrayToXml("response",$arrayIWantToConvert);
    function arrayToXml($thisNodeName,$input){
            if(is_numeric($thisNodeName))
                throw new Exception("cannot parse into xml. remainder :".print_r($input,true));
            if(!(is_array($input) || is_object($input))){
                return "<$thisNodeName>$input";
            }
            else{
                $newNode="<$thisNodeName>";
                foreach($input as $key=>$value){
                    if(is_numeric($key))
                        $key=substr($thisNodeName,0,strlen($thisNodeName)-1);
                    $newNode.=arrayToXml3($key,$value);
                }
                $newNode.="";
                return $newNode;
            }
        }
    

提交回复
热议问题