简体   繁体   中英

What's wrong with this PHP DOM code?

$doc = new DOMDocument();
$doc -> load("state.xml");
...snip...
$neworder = $doc -> createElement("order");
    $neworder -> appendChild($type);

That last line of code is causing the script to fail. 500 HTTP response. If I comment it out, the script runs fine.

get_class() confirms that both $neworder and $type are of the DOMElement class. What could the problem be?

...

On where I'm getting the nodes I'm trying to add:

This is where $type comes from.

for ($i = 0; $i < $ordersummary -> length; $i++)
{
   $o = $ordersummary -> item($i);
   $type = $o -> getElementsByTagName("type") -> item(0);
   ...

and $ordersummary is obtained like this

$ordersummary -> loadXML($_POST["data"]);
$ordersummary = $ordersummary -> getElementsByTagName("order");

The Exception is thrown because you try to append a node from one Document into another. That is not supported by the DOM API.

EDIT: The only sane workaround is to deep-copy the element. Depending on whether or not type is a complex XML structure it may be just a lot easier to serialise the type node to XML string, then create a DOMDocumentFragment for the receiving DOMDocument object and load the raw XML into this DOMDocumentFramgnent. Then you can append the DOMDocumentFragment as you would a DOMElement to insert the type XML data.

As jswolf19 pointed out, you can't append a node coming from a different document, from the documentation:

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM