0

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
apelidoko
  • 782
  • 1
  • 7
  • 23
  • Do you mean something like `$appendNode = $newNode->appendChild($reCreateOldNode);` and then add the new nodes to `$appendNode` (again using `appendChild()`). – Nigel Ren Aug 04 '20 at 18:57
  • 1
    I use https://github.com/nullivex/lib-array2xml to simplify my xml workflow that said I have always used appendXML instead of appendChild – Chris Richardson Aug 04 '20 at 19:06
  • @NigelRen after appending the child $reCreateOldNode, I wanted to append an appendXML not appendChild because I only have XML tags prepared, However I get undefined function appendXML when I try to attach the XML to the $newNode – apelidoko Aug 05 '20 at 04:02
  • Creating the XML yourself seems an odd idea when you already manipulate the DOM itself. (it also can be prone to errors). https://stackoverflow.com/questions/31144422/append-xml-to-domnode-in-php may help - it basically imports the XML and then processes the append. – Nigel Ren Aug 05 '20 at 05:53

1 Answers1

1

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>
ThW
  • 19,120
  • 3
  • 22
  • 44