(PHP 5, PHP 7, PHP 8)
DOMDocument::importNode — Importa un nodo dentro del documento actual
Esta función devuelve una copia del nodo a importar y le asocia con el documento actual.
El nodo copiado o false , si no puede ser copiado.
DOMException es lanzado si el nodo no puede ser importado.
Ejemplo #1 DOMDocument::importNode() ejemplo
Copiando nodos entre documentos.
<?php
$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");
// El nodo que se quiere importar al nuevo documento
$node = $orgdoc->getElementsByTagName("element")->item(0);
// Crear un nuevo documento
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;
// Agregar marcado
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");
echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();
// Importar el nodo y todos sus hijos al documento
$node = $newdoc->importNode($node, true);
// y entonces anexarlo a el nodo "<root>"
$newdoc->documentElement->appendChild($node);
echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>El ejemplo anterior mostrará:
The 'new document' before copying nodes into it: <?xml version="1.0"?> <root> <someelement>text in some element</someelement> </root> The 'new document' after copying the nodes into it: <?xml version="1.0"?> <root> <someelement>text in some element</someelement> <element> <child>text in child</child> </element> </root>
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:
<?php
$src = $sourcedoc->getElementById('sourceID');
$dst = $destdoc->getElementById('destID');
?>
Finally, assume that $sel has more than one child node.
In order to import the child elements of $src as children of $dst, you might do something like this:
<?php
$src = $dest->importNode($src, TRUE);
foreach ($src->childNodes as $el) $dst->appendChild($el);
?>
But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.
Therefore, the following technique should be used:
<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.
<?
$domNode = $dom->importNode($aDomNode, true);
$currentDomDocument->appendChild($domNode);
?>