SimpleXMLElement和foreach循环问题

时间:2012-01-29 21:40:14

标签: php simplexml

我有一个带两个参数的函数,第一个$methodName是一个字符串,第二个$parameters是一个数组。

function constructRequest($methodName, $parameters) {
    // converts atheme parameters to send-able XML
    $xml = new SimpleXMLElement("<methodCall></methodCall>");
    $xml->addChild("methodName", $methodName);
    $params = $xml->addChild("params");
    foreach ($parameters as $parameter) {
        $param = $xml->params->addChild("param");
        $value = $xml->params->param->addChild("value");
        $param = $xml->params->param->value->addChild("string", $parameter);
    }

    return $xml->asXML();

}

这是我的index.php

<?php

include("libatheme.php");

$test = new Atheme("nightcoast.net");
echo $test->constructRequest("atheme.login", array("yonky", "donkey", "keyhole"));
header("Content-type: text/xml");

?>

这应该产生的是:

<?xml version="1.0"?>
<methodCall>
    <methodName>atheme.login</methodName>
    <params>
        <param><value><string>yonky</string></value></param>
        <param><value><string>donkey</string></value></param>
        <param><value><string>keyhole</string></value></param>
</methodCall>

然而它会产生:

<methodCall>
<methodName>atheme.login</methodName>
<params>
<param>
<value>
<string>yonky</string>
<string>donkey</string>
<string>keyhole</string>
</value>
<value/>
<value/>
</param>
<param/>
<param/>
</params>
</methodCall>

1 个答案:

答案 0 :(得分:1)

执行此操作时,您始终引用相同的param和相同的value

$xml->params->param

$param = $xml->params->param->value

你真正想做的是:

$params = $xml->addChild("params");
foreach ($parameters as $parameter) {
    $param = $params->addChild("param");
    $value = $param->addChild("value");
    $value->addChild("string", $parameter);
}