user2791530 user2791530 - 2 years ago 273
JSON Question

Convert JSON to XML using PHP

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:


<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:

<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

$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: ;
}
}

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download