0

我最近尝试了一个简单的事情,使用 php xml writer 以更跨平台的方式输出 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();

如何在一些简单的迭代中做到这一点?

4

2 回答 2

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>
于 2013-09-30T19:45:49.650 回答
0

不是您问题的直接答案,但我强烈建议使用 JSON。它与 XML 一样跨平台兼容,但使用起来不那么冗长和麻烦。它几乎是现代 Web 服务选择的序列化方法。

使用 JSON,您的代码将是这样的:

header('Content-type: application/json');
$arr = array('param'=>'value','otherparam'=>array('vegetable'=>'tomato'));
echo json_encode($arr);
于 2013-09-30T19:51:26.610 回答