PHP - SimpleXML - AddChild with another SimpleXMLElement

后端 未结 3 952
野性不改
野性不改 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:18

    As far as I know, you can't do it with SimpleXML because addChild doesn't make a deep copy of the element (being necessary to specify the tag name can easily be overcome by calling SimpleXMLElement::getName()).

    One solution would be to use DOM instead:

    With this function:

    function sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) {
        $toDom = dom_import_simplexml($to);
        $fromDom = dom_import_simplexml($from);
        $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
    }
    

    We have for

    ");
    
    $n1 = simplexml_load_string("one");
    $n2 = simplexml_load_string("two");
    
    sxml_append($sxml, $n1);
    sxml_append($sxml, $n2);
    
    echo $sxml->asXML();
    

    the output

    
    onetwo
    

    See also some user comments that use recursive functions and addChild, e.g. this one.

提交回复
热议问题