Below is the piece of code that I am using to create a bunch of xml nodes and trying to attach to parent that is passed to it.
Not sure whats going wrong, Parent node is not getting augmented.
input.xml
<?xml version="1.0"?>
<root>
<steps> This is a step </steps>
<steps> This is also a step </steps>
</root>
output.xml should be
<?xml version="1.0">
<root>
<steps>
<step>
<step_number>1</step_number>
<step_detail>Step detail goes here</step_detail>
</step>
</steps>
<steps>
<step>
<step_number>2</step_number>
<step_detail>Step detail of the 2nd step</step_detail>
</step>
</steps>
</root>
<?php
$xml = simplexml_load_file( 'input.xml' );
$domxml = dom_import_simplexml( $xml );
//Iterating through all the STEPS node
foreach ($steps as $stp ){
createInnerSteps( &$stp, $stp->nodeValue , 'Expected Result STring' );
echo 'NODE VAL :-----' . $stp->nodeValue;// Here it should have the new nodes, but it is not
}
function createInnerSteps( &$parent )
{
$dom = new DOMDocument();
// Create Fragment, where all the inner childs gets appended
$frag = $dom->createDocumentFragment();
// Create Step Node
$stepElm = $dom->createElement('step');
$frag->appendChild( $stepElm );
// Create Step_Number Node and CDATA Section
$stepNumElm = $dom->createElement('step_number');
$cdata = $dom->createCDATASection('1');
$stepNumElm->appendChild ($cdata );
// Append Step_number to Step Node
$stepElm->appendChild( $stepNumElm );
// Create step_details and append to Step Node
$step_details = $dom->createElement('step_details');
$cdata = $dom->createCDATASection('Details');
$step_details->appendChild( $cdata );
// Append step_details to step Node
$stepElm->appendChild( $step_details );
// Add Parent Node to step element
// I get error PHP Fatal error:
// Uncaught exception 'DOMException' with message 'Wrong Document Error'
$parent->appendChild( $frag );
//echo 'PARENT : ' .$parent->saveXML();
}
?>
You are getting the
Wrong Document Errorbecause you create a newDOMDocumentobject withincreateInnerSteps(), each time it is called.When the code reaches the line
$parent->appendChild($frag), the$fragbelongs to the document created in the function and the$parentbelongs to the main document that you are trying to manipulate. You cannot move nodes (or fragments) between documents like this.The simplest solution is to only ever use the one document by replacing:
with
See a running example.
Finally, to get your desired output, you will need to remove the existing text within each
<steps>element.