SimpleXMLElement 和 foreach 循环问题
我有一个带有两个参数的函数,第一个 $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>
I have a function that takes two arguments, the first one $methodName
being a string, and the second one $parameters
being an array.
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();
}
Here's my 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");
?>
What this should produce is:
<?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>
however it produces:
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行这些操作时,您总是引用相同的
param
和相同的value
:而
您真正想要做的是:
You're always referencing the same
param
and the samevalue
when you do these:and
What you really want to do is this: