我的基本思路是遍历数组 判断当前元素有没有名为"childs"的子数组 如果有的话 递归执行本函数
$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);
if 判断的逻辑问题,你再仔细看看
php SPL里面有递归器,写起来简单点
把
$xml->endDocument();
$xml->flush();
移出 writeXml 函数,最后执行
....writeXml($config);$xml->endDocument();$xml->flush();
把
$xml->endDocument();
$xml->flush();
移出 writeXml 函数,最后执行
....writeXml($config);$xml->endDocument();$xml->flush();
整体封装成函数
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(); } }}