user775171
user775171

Reputation:

SimpleXMLElement and foreach loop issue

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>

Upvotes: 1

Views: 823

Answers (1)

Amber
Amber

Reputation: 526633

You're always referencing the same param and the same value when you do these:

$xml->params->param

and

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

What you really want to do is this:

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

Upvotes: 1

Related Questions