My basic idea is to iterate through the array to determine if the current element has a sub-array named "Childs" recursively executes this function if any
$config = Array (' root ' = = Array (' childs ' = = Array (' body ' = = = Array (' childs ' = = Array (' scroller ' = = Array (' ch Ilds ' = = Array (' header ' = = Array (' childs ' = = = Array (' simpleheader ' = = Array (' childs ' = = Array (' a ' = = Arra Y ()))), ' items ' = = Array (' childs ' = = Array (' fuck ' = = = Array (' childs ' = = = Array (' B ') ')))))))) 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 wrong? Items ran out to the outside
Reply to discussion (solution)
If you judge the logic of the problem, you take a closer look at
PHP SPL has a recursive device, which is easy to write.
Put
$xml->enddocument ();
$xml->flush ();
Remove the WRITEXML function and finally execute
WRITEXML ($config); $xml->enddocument (); $xml->flush ();
Put
$xml->enddocument ();
$xml->flush ();
Remove the WRITEXML function and finally execute
WRITEXML ($config); $xml->enddocument (); $xml->flush ();
I always thought there was a problem with the logic.
Integral encapsulation into functions
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);