Php recursively parses the array to generate xml. my basic idea is to traverse the array and determine whether the current element has a subarray named "childs". if so, recursively execute this function.
$config = array('root' => array('childs' => array('body' => array('childs' => array('scroller' => array('childs' => array('header' => array('childs' => array('simpleHeader' => array('childs' => array('a' => array())))),'items' => array('childs' => array('fuck' => array('childs' => array('b' => array())))))))))));header("Content-type:text/xml;Charset=UTF-8");$xml = new XMLWriter();$xml->openUri('php://output');$xml->startDocument('1.0', 'UTF-8');$xml->setIndent(true);function writeXml($array){global $xml;foreach($array as $key => $value){$xml->startElement($key);if( isset($value['childs']) && is_array($value['childs']) && count($value['childs']) > 0 ){writeXml($value['childs']);}$xml->endElement();}$xml->endDocument();$xml->flush();}writeXml($config);
Why is the generated xml incorrect? Items ran outside
Reply to discussion (solution)
You can take a closer look at the logic of if judgment.
Php SPL contains a recursion tool, which is easy to write.
Set
$ Xml-> endDocument ();
$ Xml-> flush ();
Remove the writeXml function and finally execute
....writeXml($config);$xml->endDocument();$xml->flush();
Set
$ Xml-> endDocument ();
$ Xml-> flush ();
Remove the writeXml function and finally execute
....writeXml($config);$xml->endDocument();$xml->flush();
I am grateful. I always thought there was a logic problem. after a long time, the problem occurred.
Encapsulated as a function
function writeXml($array, $xml=null){ if(! $xml) { header("Content-type:text/xml;Charset=UTF-8"); $xml = new XMLWriter(); $xml->openUri('php://output'); $xml->startDocument('1.0', 'UTF-8'); $xml->setIndent(true); writeXml($array, $xml); $xml->endDocument(); $xml->flush(); }else { foreach($array as $key => $value){ $xml->startElement($key); if( isset($value['childs']) && is_array($value['childs']) && count($value['childs']) > 0 ){ writeXml($value['childs'], $xml); } $xml->endElement(); } }}Call writeXml ($ config );