Heim >Backend-Entwicklung >PHP-Tutorial >php递归解析数组生成xml问题 求帮助

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-23 13:58:531086Durchsuche

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn