我最近尝试用php xml编写器以更加跨平台的方式输出db调用 - 使用xml。问题是,我想将我的多个is_array和foreach循环转换为某种循环:
$arr = array('param'=>'value','otherparam'=>array('vegetable'=>'tomato'));
$xml = new XMLWriter();
$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);
$xml->startElement('whmseo');
$xml->startElement($module);
foreach($arr as $fkey=>$fel)
{
if(is_array($fel))
{
foreach($fel as $skey=>$sel)
{
if(is_array($sel))
{
foreach($sel as $tkey=>$tel)
{
$xml->startElement($tkey);
$xml->writeRaw($tel);
$xml->endElement();
}
}
else
{
$xml->startElement($skey);
$xml->writeRaw($sel);
$xml->endElement();
}
}
}
else
{
$xml->startElement($fkey);
$xml->writeRaw($fel);
$xml->endElement();
}
}
$xml->endElement();
$xml->endElement();
header('Content-type: text/xml');
$xml->flush();
exit();
如何在一些简单的迭代中做到这一点?
答案 0 :(得分:1)
这样的东西?我无法测试XMLWriter atm ..
function xmlrecursive($xml, $key, $value) {
if (is_array($value)) {
$xml->startElement($key);
foreach ($value as $key => $sub) {
xmlrecursive($xml, $key, $sub);
}
$xml->endElement();
} else {
$xml->startElement($key);
$xml->writeRaw($value);
$xml->endElement();
}
}
$arr = array('param'=>'value','otherparam'=>array('vegetable'=>'tomato'));
$xml = new XMLWriter();
$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);
$xml->startElement('whmseo');
//$xml->startElement($module);
foreach ($value as $key => $sub) {
xmlrecursive($xml, $key, $sub);
}
//$xml->endElement();
$xml->endElement();
header('Content-type: text/xml');
$xml->flush();
exit();
输出:
<?xml version="1.0"?>
<whmseo>
<test>
<param>value</param>
<otherparam>
<vegetable>tomato</vegetable>
</otherparam>
</test>
</whmseo>
答案 1 :(得分:0)
不是您问题的直接答案,但我强烈建议您使用JSON。它与XML一样具有跨平台兼容性,但使用起来不那么冗长,也不那么麻烦。它几乎是现代Web服务的首选序列化方法。
使用JSON,您的代码将是:
header('Content-type: application/json');
$arr = array('param'=>'value','otherparam'=>array('vegetable'=>'tomato'));
echo json_encode($arr);