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:
<?php // Create a DOMDocument $doc = new DOMDocument(); Â Â // Load XML $doc->loadXML('<html></html>'); Â Â // Create an heading element on DOMDocument object $h1 = $doc->createElement('h1', "neveropen"); Â Â // 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(); ?> |
Output:
Program 2:
<?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', "neveropen"); Â Â // 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(); ?> |
Output: Press Ctrl + U to see the DOM
Reference: https://www.php.net/manual/en/domnode.clonenode.php

