PHP | DOMDocument importNode() Function

The DOMDocument::importNode() function is an inbuilt function in PHP which is used to return a copy of the node which need to import and associates it with the current document.

Syntax:

DOMNode DOMDocument::importNode( DOMNode $importedNode, bool $deep = FALSE )

Parameters: This function accepts two parameters as mentioned above and described below:



  • $importedNode: This parameter holds the node which need to import.
  • $deep: This parameter holds the Boolean value. If it set to TRUE then it will recursively import the subtree under the importedNode.

Return Value: This function returns the copied node on success or FALSE, if it cannot be copied.

Below program illustrates the DOMDocument::importNode() function in PHP:

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new document
$dom = new DOMDocument;
  
// Load the XML document
$dom->loadXML("<root><contact><email>abc@geeksforgeeks.org</email>
<mobile>+91-987654321</mobile></contact></root>");
  
// Use getElementsByTagName() function to search
// all elements with given local tag name
$node = $dom->getElementsByTagName("contact")->item(0);
  
// Create a new document
$dom1 = new DOMDocument;
  
$dom1->formatOutput = true;
  
// Load the XML document
$dom1->loadXML("<root><contactinfo><email>abc@geeksforgeeks.org</email>
<mobile>+91-987654321</mobile></contactinfo></root>");
  
echo "Document before copying the nodes\n";
  
// Save the file in XML and display it
echo $dom1->saveXML();
  
// Use importNode() function to import the node
$node = $dom1->importNode($node, true);
  
// Append child to the document
$dom1->documentElement->appendChild($node);
  
echo "\nDocument after copying the nodes\n";
  
// Save XML document and display it
echo $dom1->saveXML();
  
?>

chevron_right


Output:

Document before copying the nodes
<?xml version="1.0"?>
<root>
    <contactinfo><email>abc@geeksforgeeks.org</email>
    <mobile>+91-987654321</mobile></contactinfo>
</root>
Document after copying the nodes
<?xml version="1.0"?>
<root>
    <contactinfo><email>abc@geeksforgeeks.org</email>
    <mobile>+91-987654321</mobile></contactinfo>
    <contact><email>abc@geeksforgeeks.org</email>
    <mobile>+91-987654321</mobile></contact>
</root>

Reference: https://www.php.net/manual/en/domdocument.importnode.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.