Copying between DOM documents

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
icewind
Posts: 43
Joined: Wed Dec 31, 2008 12:41 pm UTC
Location: Netherlands
Contact:

Copying between DOM documents

Postby icewind » Sun Mar 29, 2009 1:06 pm UTC

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?

User avatar
Xanthir
My HERO!!!
Posts: 5426
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Copying between DOM documents

Postby Xanthir » Sun Mar 29, 2009 7:05 pm UTC

Can you do this with SimpleXML instead? It'd probably be easier with that.

Either way, it'll probably involve serializing.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Karrion
Posts: 92
Joined: Fri Jun 22, 2007 12:14 am UTC
Location: Melbourne, AU

Re: Copying between DOM documents

Postby Karrion » Mon Mar 30, 2009 3:00 am UTC

Does PHP's DOM Document not implement the standard importNode method?

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Copying between DOM documents

Postby mrkite » Mon Mar 30, 2009 3:31 am UTC

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.

User avatar
icewind
Posts: 43
Joined: Wed Dec 31, 2008 12:41 pm UTC
Location: Netherlands
Contact:

Re: Copying between DOM documents

Postby icewind » Mon Mar 30, 2009 6:40 pm UTC

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.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 10 guests