PHP - SimpleXML - AddChild with another SimpleXMLElement

后端 未结 3 958
野性不改
野性不改 2020-12-05 06:52

I\'m trying to build a rather complex XML document.

I have a bunch of sections of the XML document that repeats. I thought I\'d use multiple string templates as base

3条回答
  •  甜味超标
    2020-12-05 07:32

    You could use this function that is based in creating the children with attributes from the source:

    function xml_adopt($root, $new) {
        $node = $root->addChild($new->getName(), (string) $new);
        foreach($new->attributes() as $attr => $value) {
            $node->addAttribute($attr, $value);
        }
        foreach($new->children() as $ch) {
            xml_adopt($node, $ch);
        }
    }
    
    $xml = new SimpleXMLElement("");
    $child = new SimpleXMLElement("

    a paragraph

    another
    p

    "); xml_adopt($xml, $child); echo $xml->asXML()."\n";

    This will produce:

    
    

    a paragraph

    another p

提交回复
热议问题