How to convert array to SimpleXML

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

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

30条回答
  •  借酒劲吻你
    2020-11-21 07:19

    I found all of the answers to use too much code. Here is an easy way to do it:

    function to_xml(SimpleXMLElement $object, array $data)
    {   
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $new_object = $object->addChild($key);
                to_xml($new_object, $value);
            } else {
                // if the key is an integer, it needs text with it to actually work.
                if ($key != 0 && $key == (int) $key) {
                    $key = "key_$key";
                }
    
                $object->addChild($key, $value);
            }   
        }   
    }   
    

    Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:

    $xml = new SimpleXMLElement('');
    to_xml($xml, $my_array);
    

    Now $xml contains a beautiful XML object based on your array exactly how you wrote it.

    print $xml->asXML();
    

提交回复
热议问题