How to convert array to SimpleXML

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

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

30条回答
  •  太阳男子
    2020-11-21 07:23

    Whole XML structure is defined in $data Array:

    function array2Xml($data, $xml = null)
    {
        if (is_null($xml)) {
            $xml = simplexml_load_string('<' . key($data) . '/>');
            $data = current($data);
            $return = true;
        }
        if (is_array($data)) {
            foreach ($data as $name => $value) {
                array2Xml($value, is_numeric($name) ? $xml : $xml->addChild($name));
            }
        } else {
            $xml->{0} = $data;
        }
        if (!empty($return)) {
            return $xml->asXML();
        }
    }
    

提交回复
热议问题