下面是我用来创建一堆 xml 节点并尝试附加到传递给它的父节点的代码。
不知道出了什么问题,父节点没有得到增强。
输入.xml
<?xml version="1.0"?>
<root>
<steps> This is a step </steps>
<steps> This is also a step </steps>
</root>
output.xml 应该是
<?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();
}
?>