0

Creating the DOMDocument object:

$getToken = '<getToken>...</getToken>';
$getToken_objeto = new DOMDocument("1.0", "UTF-8");
$getToken_objeto -> loadXML($getToken);

Trying to append a XML string (Signature) into the DOMDocument created above:

$Signature = '<Signature>...</Signature>';
$Signature_objeto = new DOMDocument("1.0", "UTF-8");
$Signature_objeto -> loadXML($Signature);
$Signature_nodeList = $Signature_objeto -> getElementsByTagName("Signature");
$Signature_node = $Signature_nodeList -> item(0);
$getToken_objeto -> importNode($Signature_node, true);
$getToken_objeto -> appendChild($Signature_node);

I get 2 errors:

Fatal error: Uncaught exception 'DOMException' with message 'Wrong Document Error' in C:... DOMException: Wrong Document Error in C:...

Seems simple to resolve but im quite unexperienced using the PHP DOM extension.

Thanks in advance.

1 Answer 1

4

You're trying to append the original node - not the imported one.

$Signature_node = $getToken_objeto->importNode(
  $Signature_nodeList->item(0), true
);

You're trying to append the node to the document, but an XML document can only have a single document element and it already has one. You can append it to the document element:

$getToken_objeto->documentElement->appendChild($Signature_node);

But PHP can load XML fragments directly into a DOMDocumentFragment.

$xml = '<getToken>...</getToken>';
$fragmentXml = '<Signature>...</Signature>';

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);

$fragment = $dom->createDocumentFragment();
$fragment->appendXml($fragmentXml);

$xpath
  ->evaluate('//getToken')
  ->item(0)
  ->appendChild($fragment);

echo $dom->saveXml();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ThW worked perfectly and helps me understand and learn more the PHP DOM extension :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.