douyu7210 2013-10-28 23:17
浏览 34
已采纳

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

  • 写回答

2条回答 默认 最新

  • dongxiangchan0743 2013-10-28 23:25
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序