Import node into current document

DOMDocument::importNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::importNodeImport node into current document

說明

public DOMDocument::importNode(DOMNode $node, bool $deep = false): DOMNode|false

This function returns a copy of the node to import and associates it with the current document.

參數

node

The node to import.

deep

If set to true, this method will recursively import the subtree under the node.

注意:

To copy the nodes attributes deep needs to be set to true

返回值

The copied node or false, if it cannot be copied.

錯誤/異常

DOMException is thrown if node cannot be imported.

範例

示例 #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc 
= new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node $orgdoc->getElementsByTagName("element")->item(0);


// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo 
"The 'new document' before copying nodes into it:\n";
echo 
$newdoc->saveXML();

// Import the node, and all its children, to the document
$node $newdoc->importNode($nodetrue);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo 
"\nThe 'new document' after copying the nodes into it:\n";
echo 
$newdoc->saveXML();
?>

以上例程會輸出:

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>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *