Home >Backend Development >PHP Tutorial >php递归解析数组生成xml问题 求帮助

php递归解析数组生成xml问题 求帮助

WBOY
WBOYOriginal
2016-06-23 13:58:531069browse

我的基本思路是遍历数组 判断当前元素有没有名为"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);

为什么生成的xml不对? items跑到了外面 如图


回复讨论(解决方案)

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();    }  }}
调用 writeXml($config);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn