DOMDocument::importNode

(PHP 5)

DOMDocument::importNode — Импорт узла в текущий документ


Описание

public DOMNode DOMDocument::importNode ( DOMNode $importedNode [, bool $deep ] )

Эта функция возвращает копию импортируемого узла и присоединяет ее к текущему документу.


Список параметров

importedNode

- Импортируемый узел.

deep

- Если установлен в TRUE, этот метод рекурсивно импортирует поддерево узла importedNode.

Замечание:

Чтобы скопировались атрибуты узла, deep должен быть установлен в TRUE.


Возвращаемые значения

Скопированный узел или FALSE, если он не может быть скопирован.


Ошибки

Если узел не может быть импортирован, будет выброшено исключение DOMException.


Примеры

Пример #1 Пример использования DOMDocument::importNode()

Копирование узлов между документами.


$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");
// Узел, который будет импортирован в новый документ
$node = $orgdoc->getElementsByTagName("element")->item(0);
// Создание нового документа
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;
// Добавление разметки
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");
echo "Новый документ перед добавлением в него узлов:\n";
echo $newdoc->saveXML();
// Импорт узла и всех его потомков в документ
$node = $newdoc->importNode($node, true);
// И затем добавление узла в корень элемента
$newdoc->documentElement->appendChild($node);
echo "\nНовый документ после добавления в него узлов:\n";
echo $newdoc->saveXML();

Результат выполнения данного примера:


Новый документ перед добавлением в него узлов:
<?xml version="1.0"?>
<root>
<someelement>text in some element</someelement>
</root>

Новый документ после добавления в него узлов:
<?xml version="1.0"?>
<root>
<someelement>text in some element</someelement>
<element>
<child>text in child</child>
</element>
</root>


$xml="
<html>
<a href='yandex.com'>Yandex.com</a>
<a href='rik.dn.ua'>RiK.dn.ua</a>
</html>
";
$doc=new domDocument('1.0');
$doc->loadXML($xml);
$list=$doc->getElementsByTagName('a');
$doc1=new domDocument('1.0');
$doc1->formatOutput=true;
for($i=0; $i<$list->length; $i++) $doc1->appendChild($doc1->importNode($list->item($i), false));
$doc1->save('file.xml');


2
c dot 1 at smithies dot org5 years ago
$src = $sourcedoc->getElementById('sourceID');
$dst = $destdoc->getElementById('destID');


1
p dot reisinger at gmail dot com6 years ago
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\


1
Colin8 years ago
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;
        
        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);
        $node = $DOMParent->importNode($node, true);
        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }
        return $DOMParent->saveXML();
    }


0
mailme at sove dot nl6 years ago
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:
$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );
$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.


0
mark at 4inloop dot de7 years ago
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.


0
adjwilli8 years ago
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.
Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).
$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string
        
function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {
            
        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);
        
        $newNode = $doc->importNode($xmlPost->firstChild,true);
        
        $node->parentNode->replaceChild($newNode,$node);
    } else {
        
        $page = 1;
        $section = 1;
        
        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}
    
nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath
    
$doc->saveXML();


0
stomas8 years ago
I think this should do the same:
<?
// Import $b into $a's document
function myimport($a, $b)
{
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
}
?>


0
andy dot clark at dial dot pipex dot com8 years ago
One useful use of importNode is to copy one node onto another.
function CopyXMLNode($SourceNode,$DestNode)
{
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }


0
Fitopaldi9 years ago
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);
?>


Описание класса domdocument, примеры использования класса domdocument.



Смотрите также:
Описание на ru2.php.net
Описание на php.ru