How to convert array to SimpleXML

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

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

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

    I would have commented the second most voted answer, because it doesn't preserve structure and generates bad xml if there is numerically indexed inner arrays.

    I developed my own version based on it, because I needed simple converter between json and xml regardless of the structure of data. My version preserves numeric key information and structure of the original array. It creates elements for the numerically indexed values by wrapping values to value -named elements with key-attribute that contains numerical key.

    For example

    array('test' => array(0 => 'some value', 1 => 'other'))

    converts to

    some valueother

    My version of array_to_xml -function (hope it helps somebody :)

    function array_to_xml($arr, &$xml) {
        foreach($arr as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml->addChild("$key");
                } else {
                    $subnode = $xml->addChild("value");
                    $subnode->addAttribute('key', $key);                    
                }
                array_to_xml($value, $subnode);
            }
            else {
                if (is_numeric($key)) {
                    $xml->addChild("value", $value)->addAttribute('key', $key);
                } else {
                    $xml->addChild("$key",$value);
                }
            }
        }
    }   
    

提交回复
热议问题