How to change root of a node with DomDocument methods?

后端 未结 5 1125
执念已碎
执念已碎 2021-01-16 10:05

How to only change root\'s tag name of a DOM node?

In the DOM-Document model we can not change the property documentElement of a DOMElement

5条回答
  •  被撕碎了的回忆
    2021-01-16 11:03

    First, you need to understand that the DOMDocument is only the hierarchical root of the document-tree. It's name is always #document. You want to rename the root-element, which is the $document->documentElement.

    If you want to copy nodes form a document to another document, you'll need to use the importNode() function: $document->importNode($nodeInAnotherDocument)

    Edit:

    renameNode() is not implemented yet, so you should make another root, and simply replace it with the old one. If you use DOMDocument->createElement() you don't need to use importNode() on it later.

    $oldRoot = $doc->documentElement;
    $newRoot = $doc->createElement('new-root');
    
    foreach ($oldRoot->attributes as $attr) {
      $newRoot->setAttribute($attr->nodeName, $attr->nodeValue);
    }
    
    while ($oldRoot->firstChild) {
      $newRoot->appendChild($oldRoot->firstChild);
    }
    
    $doc->replaceChild($newRoot, $oldRoot); 
    

提交回复
热议问题