假设您有以下数组:
$nodes = array(
"parent node",
"parent node",
array(
"child node",
"child node",
array(
"grand child node",
"grand child node")));
您将如何将其转换为XML字符串,使其看起来像:
<node>
<node>parent node</node>
<node>parent node</node>
<node>
<node>child node</node>
<node>child node</node>
<node>
<node>grand child node</node>
<node>grand child node</node>
</node>
</node>
</node>
function traverse($nodes)
{
echo "<node>";
foreach($nodes as $node)
{
if(is_array($node))
{
traverse($node);
}
else
{
echo "<node>$node</node>";
}
}
echo "</node>";
}
traverse($nodes);
我正在寻找一种使用迭代的方法.
解决方法:
<?PHP
$nodes = array(
"parent node",
"parent node",
array(
"child node",
"child node",
array(
"grand child node",
"grand child node"
)
)
);
$s = '<node>';
$arr = $nodes;
while(count($arr) > 0)
{
$n = array_shift($arr);
if(is_array($n))
{
array_unshift($arr, null);
$arr = array_merge($n, $arr);
$s .= '<node>';
}
elseif(is_null($n))
$s .= '</node>';
else
$s .= '<node>'.$n.'</node>';
}
$s .= '</node>';
echo $s;
?>