Array不会转换为XML

I have this array ($data):

Array (
    [status_code] => X
    [key_1] => 12345
    [key_2] => 67890
    [short_message] => test
    [long_message] => test_long_message
)

But I am struggling to convert this to an XML element.

Here is my code:

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($data, array ($xml, 'addChild'));
print $xml->asXML();

Here is the results I am wanting:

<root>
    <status_code>X</status_code>
    <key_1>12345</key_1>
    <key_2>67890</key_2>
    <short_message>test</short_message>
    <long_message>test_long_message</long_message>
</root>

Instead I get:

<X>1234567890testtest_message_long

Could somebody please point out what I am doing wrong?

Thanks,

Peter

SimpleXMLElement.addChild() takes its parameters in the order $elementName, $elementValue.

array_walk_recursive() passes the elements in the order $value, $key (in your example that would be $elementValue, $elementName).

This should work:

$data = array(
    'status_code' => 'X',
    'key_1' => 12345
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive(
    $data,
    function ($value, $key) use ($xml) {
        $xml->addChild($key, $value);
    }
);
echo $xml->asXML();

Just write it out, it's much easier to read and change:

foreach ($data as $name => $value) {
    $xml->$name = $value;
}

It's not always necessary to just have a callback when a simple foreach can do. Howver, creating a utility function isn't that bad either:

function simplexml_add_array(SimpleXMLElement $xml, array $data) {
    foreach ($data as $name => $value) {
        $xml[$name] = $value;
    }
}

And then finally by inheritence (Demo):

class SimplerXMLElement extends SimpleXMLElement
{
    public function addArray(array $data) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}


$xml = new SimplerXMLElement ('<root/>');
$xml->addArray($data);
print $xml->asXML();

Program Output (beautified):

<?xml version="1.0"?>
<root>
  <status_code>X</status_code>
  <key_1>12345</key_1>
  <key_2>67890</key_2>
  <short_message>test</short_message>
  <long_message>test_long_message</long_message>
</root>