How to convert array to SimpleXML

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

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

30条回答
  •  余生分开走
    2020-11-21 07:11

    So anyway... I took onokazu's code (thanks!) and added the ability to have repeated tags in XML, it also supports attributes, hope someone finds it useful!

      $v) {
    
                $attrArr = array();
                $kArray = explode(' ',$k);
                $tag = array_shift($kArray);
    
                if (count($kArray) > 0) {
                    foreach($kArray as $attrValue) {
                        $attrArr[] = explode('=',$attrValue);                   
                    }
                }
    
                if (is_array($v)) {
                    if (is_numeric($k)) {
                        array_to_xml($v, $xml);
                    } else {
                        $child = $xml->addChild($tag);
                        if (isset($attrArr)) {
                            foreach($attrArr as $attrArrV) {
                                $child->addAttribute($attrArrV[0],$attrArrV[1]);
                            }
                        }                   
                        array_to_xml($v, $child);
                    }
                } else {
                    $child = $xml->addChild($tag, $v);
                    if (isset($attrArr)) {
                        foreach($attrArr as $attrArrV) {
                            $child->addAttribute($attrArrV[0],$attrArrV[1]);
                        }
                    }
                }               
            }
    
            return $xml;
        }
    
            $test_array = array (
              'bla' => 'blub',
              'foo' => 'bar',
              'another_array' => array (
                array('stack' => 'overflow'),
                array('stack' => 'overflow'),
                array('stack' => 'overflow'),
              ),
              'foo attribute1=value1 attribute2=value2' => 'bar',
            );  
    
            $xml = array_to_xml($test_array, new SimpleXMLElement(''))->asXML();
    
            echo "$xml\n";
            $dom = new DOMDocument;
            $dom->preserveWhiteSpace = FALSE;
            $dom->loadXML($xml);
            $dom->formatOutput = TRUE;
            echo $dom->saveXml();
        ?>
    

提交回复
热议问题