How to Clone an XML Node using PHP

Cloning
an XML node is useful if you want to copy an existing xml node and then make the
necessary changes to it to make it a unique one. To do this task PHP provides
you with a cloneNode function that can be used to clone an existing node.

If
you look at the above XML file you will find that the candidate node can be cloned
and then easily modified to include another candidate. So, in this example we
will be cloning the first node which has the attribute "id" as "candid".
The code that performs this action is given below:

In
the above code a new DOMDocument is added and then the XML file is added to it.
In the above example the variables $xp is used to store the xpath, $qry is used
to store the query, and the $xpQry is used to store the xpathquery. We use a 'for
loop' to clone the node. In that we do two type of cloning. One is the deep cloning
where you get all the elements of the node and the other is the shallow cloning
where we get only the node. We set an attribute named "cloned" to identify
whether that node is cloned or not.

The
result of the above code will give you an XML file whose content will be as follows: