Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
311
DOMNode Function cloneNode
PHP Version: (No version information might be only in CVS. I have used this function
in PHP5)
DOM: W3C
DOM Level 2
Description
This function creates a copy of the node. This is
required when you want to copy a node and wants to modify it, without touching
the original node. Please see the example for more details.
Usage:
objectDOMNode->cloneNode ( [bool deep])
Creates a
copy of the node. The parameter deep
indicates whether to copy all descendant nodes. This parameter is defaulted to
FALSE.
//creates a new domXPath object by passing the DOM Document
$xpath
= new domXPath($dom);
//create a new query
$query =
"//employee";
//execute the xpath query
$xpathQuery
= $xpath->query($query);
$size = $xpathQuery->length;
for ($i=0; $i<$size; $i++){
$node = $xpathQuery->item($i);
if($i==0){
//perform the deep cloning for first
attribute
$clonenode =
$node->cloneNode(true);
}else{
//clone only the node, not its child
$clonenode =
$node->cloneNode(false);
}
//create an attribute so that you can know
that it is cloned
$clonenode->setAttribute('cloned',$i);
$company->appendChild($clonenode);
echo "<HTML>";
echo "<Head>";
echo "<title>Example of DOMNode->cloneNode</title>";
echo "<Head>";
echo "<body>";
echo "<PRE>";
echohtmlentities($dom ->saveXML());
echo "</PRE>";
echo "</body>";
echo "</HTML>";
?>
Output:
The expected
output would be:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee>
<employeename id="myId">test1</employeename>
<employeeaddress>testAddress1</employeeaddress>
<SSN>11111</SSN>
<company>XYZ Corporation</company>
</employee><employee>
<employeename id="myId1">test1</employeename>
<employeeaddress>testAddress1</employeeaddress>
<SSN>11111</SSN>
<company>ABC Corporation</company>
</employee>
<!--This is the deep cloning so child also included -->
<employee cloned="0">
<employeename id="myId">test1</employeename>
<employeeaddress>testAddress1</employeeaddress>
<SSN>11111</SSN>
<company>XYZ Corporation</company>
<!--This is the shallow cloning only the node is cloned -->
</employee><employee cloned="1"/>
</company>