php - DOMDocument How to Append to newly Appended Child Element in createDocumentFragment?

Hi I wanted to know how to append an XML tag in a newly created Appended Child Node?

Here is what I have,

$newNode = $xml->createDocumentFragment();
$reCreateOldNode = $xml->createElement("myNewChild");
$newNode->appendChild($reCreateOldNode);         // This is Newly Appended Child
   while ($node->firstChild) {
     $match->nodeValue = "";
     $newNode->appendChild($node->firstChild);
     $newNode->appendXML($actionOutput);        // I want to Append the XML to $newNode->myNewChild
   }
$node->parentNode->replaceChild($newNode, $node);

This is the newly created Child,

$newNode->appendChild($reCreateOldNode);  

And I want to Append the XML that I have created to $newNode->myNewChild not on $newNode directly.

Answer

Solution:

The actual purpose of a document fragment is to allow you to treat a list of nodes (elements, text nodes, comments...) as a single node and use them as an argument to the DOM methods. You only want to append a single node (and its descendants) - no need to append this node to a fragment.

In PHP the document fragment can parse an XML fragment string. So you can use it to parse a string as an XML snippet and then append it to a DOM node. This fragment will be appended to new node.

$document = new DOMDocument();
$document->loadXML('<old>sample<foo/></old>');
$node = $document->documentElement;

// create the new element and store it in a variable
$newNode = $document->createElement('new');
// move over all the children from "old" $node
while ($childNode = $node->firstChild) {
    $newNode->appendChild($childNode);
}

// create the fragment for the XML snippet
$fragment = $document->createDocumentFragment();
$fragment->appendXML('<tag/>text');

// append the nodes from the snippet to the new element
$newNode->appendChild($fragment);

$node->parentNode->replaceChild($newNode, $node);

echo $document->saveXML();

Output:

<?xml version="1.0"?>
<new>sample<foo/><tag/>text</new>

Source