PHP | DOMNode cloneNode() function

The DOMNode::cloneNode() function is an inbuilt function in PHP which is used to create a copy of the node.

Syntax:

DOMNode DOMNode::cloneNode( bool $deep )

Parameters:This function accepts a single parameter $deep which indicates whether to copy all descendant nodes. This parameter is set to FALSE by default.



Return Value: This function returns the cloned node.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Create a DOMDocument
$doc = new DOMDocument();
  
// Load XML
$doc->loadXML('<html></html>');
  
// Create an heading element on DOMDocument object
$h1 = $doc->createElement('h1', "geeksforgeeks");
  
// Append the child
$doc->documentElement->appendChild($h1);
  
// Create a new DOMDocument
$doc_new = new DOMDocument();
  
// Deep clone the node to new instance
$doc_new = $doc->cloneNode(true);
  
// Render the cloned instance
echo $doc_new->saveXML();
?>

chevron_right


Output:

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Create a DOMDocument
$doc = new DOMDocument('1.0', 'iso-8859-1');
  
// Load XML
$doc->loadXML('<html></html>');
  
// Create an heading element on DOMDocument object
$h1 = $doc->createElement('h1', "geeksforgeeks");
  
// Append the child
$doc->documentElement->appendChild($h1);
  
// Shallow clone the node to a new instance
// It will clone only the instance not its
// children nodes
$doc_new = $doc->cloneNode(false);
  
// Render the cloned instance
echo $doc_new->saveXML();
?>

chevron_right


Output: Press Ctrl + U to see the DOM

Reference: https://www.php.net/manual/en/domnode.clonenode.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.