使用 PHP 将 JSON 转换为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19118925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON to XML using PHP
提问by user2791530
My Task is to convert the JSON data in to XML. Right now, My array_to_xml function converts the data from the array into:
我的任务是将 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>
<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>
I would like to have the XML in the following format:
我想要以下格式的 XML:
<Maserati> 1 </Maserati>
<BMW> 2 </BMW>
...
Please take a look at the PHP below and let me know the changes to be made. Thanks in advance
请查看下面的 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: ;
}
}
采纳答案by Rully Hendrawan
It has been explained here: Is there some way to convert json to xml in PHP?
这里已经解释过了: Is there some way to convert json to xml in PHP?