0
下面是我用來創建一堆xml節點並嘗試附加到傳遞給它的父代的一段代碼。在domdocument中創建XML片段並添加到它的父代
不知道是怎麼回事,父節點沒有得到增強。
的input.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();
}
?>
非常感謝:) – nepsdotin