Page 1 of 1

Copying between DOM documents

Posted: Sun Mar 29, 2009 1:06 pm UTC
by icewind
I'm working on a part of a site in PHP that uses an XML file as source and generates another XML document as output.

But I have one problem I can't seem to find a way to clone a node from the source document to the target document.
What I need is an exact copy of a node without it's childs but the problem is that I don't know how to get it from the one DOMDocument to the other.

Do you know any way to do this?

Re: Copying between DOM documents

Posted: Sun Mar 29, 2009 7:05 pm UTC
by Xanthir
Can you do this with SimpleXML instead? It'd probably be easier with that.

Either way, it'll probably involve serializing.

Re: Copying between DOM documents

Posted: Mon Mar 30, 2009 3:00 am UTC
by Karrion
Does PHP's DOM Document not implement the standard importNode method?

Re: Copying between DOM documents

Posted: Mon Mar 30, 2009 3:31 am UTC
by mrkite
icewind wrote:I'm working on a part of a site in PHP that uses an XML file as source and generates another XML document as output.

But I have one problem I can't seem to find a way to clone a node from the source document to the target document.
What I need is an exact copy of a node without it's childs but the problem is that I don't know how to get it from the one DOMDocument to the other.

Do you know any way to do this?


Yeah, here's how:

Code: Select all

$src=simplexml_load_string($srcXML);
$dest=simplexml_load_string($destXML);

$dom=dom_import_simplexml($dest->container);
$node=$dom->ownerDocument->importNode(dom_import_simplexml($src->child),true);
$dom->appendChild($node);


Confusing, I know. Basically takes <child></child> from srcXML and appends it to
<container></container> in destXML.

Re: Copying between DOM documents

Posted: Mon Mar 30, 2009 6:40 pm UTC
by icewind
Xanthir wrote:Can you do this with SimpleXML instead? It'd probably be easier with that.

I can't use simple XML because that doesn't have support for mixed content (an element with both child nodes and text).
Karrion wrote:Does PHP's DOM Document not implement the standard importNode method?

It seems it does, thanks, that would probably do the trick.