For some reason the php community decided to completely neglect the documentation for their DOMDocument API. Only a few of the more popular functions have any documentation; and of that fraction the documentation is less than helpful. With the onset of the web 2.0 (r(ev))oluvtion, most PHP programmers will soon realize the importance of knowing how to navigate and work with the DOM in an efficient manner.
I just spent the last hour or so trying to understand why the DOMDocument API will not allow for two seperate documents to be merged, that is, why could I not append a DOMNode from Document A to a DOMNode of Document B. I can only assume that this is a security feature that just isn’t very apparent to me right now. However, this seems — to me atleast — to be a pretty common task and should be relatively intuitive. Unfortunately, like most things in life, it’s excessively complicated.
Rambling aside, after digging into the books and trying to find more details on the DOMDocument, I happened upon the DOMDocumentFrament class. A class which has very little documentation and also happens to solve my problem. Here’s the excessively complicated solution:
$documentA = new DOMDocument("1.0"); $rootA = $documentA->createElement("root"); $documentA->appendChild($rootA); $documentB = DOMDocument::load("/path/to/file"); $frag = $documentB->createDocumentFragment(); $frag->appendXML($documentA->saveXML($rootA)); $documentB->appendChild($frag);
Obviously this is a very trivial example, but hopefully the point is clear. If you want to take an element from a given document and append it to another document, the solution above will do the trick