Copying HTML from a document to another document
| From: | Sam Hobbs | Date: | Fri, 03 Sep 2004 04:01:41 +0000 |
| Subject: | Copying HTML from a document to another document | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-195674@lists.php.net to get a copy of this message | ||
I need to copy HTML from a DOM document to another DOM document. The
following is a simplified version of what I need to do.
// Create HTML to be copied from
$ContentsDocument = new DOMDocument();
$TextNode = $ContentsDocument->createTextNode("Text");
$Paragraph = $ContentsDocument->createElement("P");
$Paragraph->appendChild($TextNode);
$ContentsDocument->appendChild($Paragraph);
// Create a table to copy to
$Document = new DOMDocument();
$Cell = $Document->createElement("TD");
$Row = $Document->createElement("TR");
$Row->appendChild($Cell);
$Table = $Document->createElement("Table");
$Table->appendChild($Row);
$Document->appendChild($Table);
// Copy and save
foreach($ContentsDocument->childNodes as $Node)
$Cell->appendChild($Node);
print $Document->saveHTML();
This works, except I get the error:
Fatal error: Uncaught exception 'DOMException' with message 'Wrong
Document Error'
from the appendChild. I tried many things and everything I tried either got
that error or copied nothing. So I converted the code to JavaScript, and the
JavaScript version works. The JavaScript code uses:
Nodes = ContentsDocument.childNodes;
while(Node = Nodes.nextNode())
Cell.appendChild(Node);
instead of:
foreach($ContentsDocument->childNodes as $Node)
$Cell->appendChild($Node);
So how can I do it in PHP also?