Reputation: 69
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: ;
}
}
Upvotes: 1
Views: 27603
Reputation: 154
It has been explained here: Is there some way to convert json to xml in PHP?
Use json_decode() and PEAR::XML_Serializer
Upvotes: 1