1

我的任务是将 JSON 数据转换为 XML。现在,我的 array_to_xml 函数将数组中的数据转换为:

<0>Maserati</0><1>BMW</1><2>Mercedes/2><3>Ford</3><4>Chrysler</4><5>Acura</5><6>Honda</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6>

我希望 XML 采用以下格式:

  <Maserati> 1 </Maserati>
  <BMW> 2 </BMW>
  ...

请查看下面的 PHP 并让我知道要进行的更改。提前致谢

$inpData =  $_POST['data'];
// initializing array
$inp_info =  $inpData;
// creating object of SimpleXMLElement
$xml_inp_info = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"   standalone=\"yes\"?><demandSignals>\n</demandSignals>\n");
// function call to convert array to xml
array_to_xml($inp_info,$xml_inp_info);
//saving generated xml file
$xml_inp_info->asXML(dirname(__FILE__)."/demand.xml") ;
// function definition to convert array to xml
function array_to_xml($inp_info, &$xml_inp_info) {
        foreach($inp_info as $key => $value) {

            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml_inp_info->addChild("$key"); 
                    if(count($value) >1 && is_array($value)){
                        $jump = false;
                        $count = 1;
                        foreach($value as $k => $v) {
                            if(is_array($v)){
                                if($count++ > 1)
                                    $subnode = $xml_inp_info->addChild("$key");

                                array_to_xml($v, "$subnode");
                                $jump = true;
                            }
                        }
                        if($jump) {
                            goto LE;
                        }
                        array_to_xml($value, "\n$subnode");
                        }
                    else
                        array_to_xml($value, $subnode);
                }
                else{
                    array_to_xml($value, $xml_inp_info);
                }
            }
            else {

                $xml_inp_info->addChild("$key","$value");
            }

            LE: ;
        }
    }
4

1 回答 1

1

这里已经解释过: 有什么方法可以在 PHP 中将 json 转换为 xml?

使用json_decode()PEAR::XML_Serializer

于 2013-10-01T14:41:33.973 回答