How to convert array to SimpleXML

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

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

30条回答
  •  难免孤独
    2020-11-21 07:34

    My answer, cobbling together others' answers. This should correct for the failure to compensate for numeric keys:

    function array_to_xml($array, $root, $element) {
        $xml = new SimpleXMLElement("<{$root}/>");
        foreach ($array as $value) {
            $elem = $xml->addChild($element);
            xml_recurse_child($elem, $value);
        }
        return $xml;
    }
    
    function xml_recurse_child(&$node, $child) {
        foreach ($child as $key=>$value) {
            if(is_array($value)) {
                foreach ($value as $k => $v) {
                    if(is_numeric($k)){
                        xml_recurse_child($node, array($key => $v));
                    }
                    else {
                        $subnode = $node->addChild($key);
                        xml_recurse_child($subnode, $value);
                    }
                }
            }
            else {
                $node->addChild($key, $value);
            }
        }   
    }
    

    The array_to_xml() function presumes that the array is made up of numeric keys first. If your array had an initial element, you would drop the foreach() and $elem statements from the array_to_xml() function and just pass $xml instead.

提交回复
热议问题