huowz 发表于 2014-04-30 08:59

数组转XML出错,好像没有遍历数组?

有一段代码,想要将数组转化为xml格式:<?php
       
                $msg ['ToUserName'] = 'o79ortyr_MsY3o_BgdEQYDpi1M48';
                $msg ['FromUserName'] = 'gh_7fbd286b23b3';
                $msg ['CreateTime'] = 1398763870;
                $msg ['MsgType'] = 'text';

      $xmlmsg = '
                <xml>
                        <ToUserName>
                                <!]>               
                        </ToUserName>
                        <FromUserName>
                                <!]>               
                        </FromUserName>
                        <CreateTime>1398763870</CreateTime>
                        <MsgType>
                                <!]>               
                        </MsgType>
                        <Content>
                                <!]>               
                        </Content>
                </xml>
                ';               
      $xmlm = new \SimpleXMLElement ( $xmlmsg );

      _data2xml ( $xmlm, $msg, 'item' );
               
                $str = $xmlm->asXML ();
                       
                // 记录日志

               
             print_r ($str);
       
                function _data2xml($xmls, $data, $item = 'item') {
               print_r ( $data );
                foreach ( $data as $key => $value ) {
                        is_numeric ( $key ) && ($key = $item);
                        echo ($key .'-->'. $value);
                        if (is_array ( $value ) || is_object ( $value )) {
                            $child = $xmls->addChild ( $key );
                                _data2xml ( $child, $value, $item );
                        } else {                     
                                if (is_numeric ( $value )) {

                                        $child = $xmls->addChild ( $key, $value );
                                } else {
                                        $child = $xmls->addChild ( $key );
                                        $node = dom_import_simplexml ( $child );
                                        $node->appendChild ( $node->ownerDocument->createCDATASection ( $value ) );
               
                                }
                        }
                }
        }
?>
运行以后得到的是这样的:
Array ( => o79ortyr_MsY3o_BgdEQYDpi1M48 => gh_7fbd286b23b3 => 1398763870 => text ) ToUserName-->o79ortyr_MsY3o_BgdEQYDpi1M48
好像没有遍历数组,不知道哪里错了?
页: [1]
查看完整版本: 数组转XML出错,好像没有遍历数组?