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

Post an example of the input json.

Are you able to edit the json format?

Json format data
is
{ “data”:[[“Cars”,“Maserati”,“Mazda”,“Mercedes”,“Mini”,“Mitsubishi”],[“2009”,“0”,“2941”,“4303”,“35]4”,“5814”],[“2010”,“5”,“2905”,“2867”,“412”,“5284”],[“2011”,“4”,“2517”,“4822”,“552”,“6127”]]}

Rightnow, Its converting the above data into xml in the following format
<0>cars</0><1>Maserati</1> etc…
But, I want the xml to be in the following format

1
4 etc

I can edit the Json format. But, Per the requirement, it has to be automatically converted into xml, once the user hits the submit button.
Thanks for looking into the issue

What is the logic behind the different numbers here:

"data": [ [ "Cars", "Maserati", "Mazda", "Mercedes", "Mini", "Mitsubishi" ], [ "2009", "0", "2941", "4303", "35]4", "5814" ], [ "2010", "5", "2905", "2867", "412", "5284" ], [ "2011", "4", "2517", "4822", "552", "6127" ] ]

And the same here, where do you get 1 & 4 from?

<cars> <Maserati> 1</Maserati> <Mazda> 4 </Mazda> etc

This should get you going anyway.

First off, this layout made more sense for the JSON, didn’t know what the numbers were so removed them.

{"data":{"cars":["Maserati","Mazda","Mercedes","Mini","Mitsubishi"]}}

Then you can just do something like this, again didn’t know what the numbers were, so replace the rand function with whatever logic you want to get numbers :slight_smile:
[php]<?php
$json = ‘{“data”:{“cars”:[“Maserati”,“Mazda”,“Mercedes”,“Mini”,“Mitsubishi”]}}’;
$jsonDecoded = json_decode($json);

$xml = new SimpleXMLElement(’’);
foreach ($jsonDecoded->data->cars as $car) {
$xml->addChild($car, rand(0,10));
}
print $xml->asXML();[/php]

Output:

<?xml version="1.0"?> <cars> <Maserati>7</Maserati> <Mazda>4</Mazda> <Mercedes>0</Mercedes> <Mini>4</Mini> <Mitsubishi>9</Mitsubishi> </cars>

The json format is
“data”: [
[
“Year”,
“Maserati”,
“Mazda”,
“Mercedes”,
“Mini”,
“Mitsubishi”
],
[
“2009”,
“0”,
“2941”,
“4303”,
“35]4”,
“5814”
],
[
“2010”,
“5”,
“2905”,
“2867”,
“412”,
“5284”
]]
xml format i need is 2009
0
2941

Sorry for the confusion

That format would be invalid, I will assume you meant this:

<cars> <2009> <Maserati>0</Maserati> <Mazda>2941</Mazda> </2009> <2010> <Maserati>5</Maserati> <Mazda>2905</Mazda> </2010> </cars>

I would suggest changing the JSON to this:

{"data":{"cars":["Maserati","Mazda","Mercedes","Mini","Mitsubishi"],"year":{"2009":[0,2941,4303,3504,5814],"2010":[5,2905,2867,412,5284],"2011":[4,2517,4822,552,6127]}}}

Compare the two json strings on http://jsonlint.com and you will see how the new structure is better.

Possible solution:
[php]$json = ‘{“data”:{“cars”:[“Maserati”,“Mazda”,“Mercedes”,“Mini”,“Mitsubishi”],“year”:{“2009”:[0,2941,4303,3504,5814],“2010”:[5,2905,2867,412,5284],“2011”:[4,2517,4822,552,6127]}}}’;
$jsonDecoded = json_decode($json);

$xml = new SimpleXMLElement(’’);
foreach ($jsonDecoded->data->year as $year => $production) {
$xmlyear = $xml->addChild($year);

$i = 0;
foreach ($jsonDecoded->data->cars as $car) {
$xmlyear->addChild($car, $production[$i]);
$i++;
}

}
print $xml->asXML();[/php]

Output:

<?xml version="1.0"?> <cars> <2009> <Maserati>0</Maserati> <Mazda>2941</Mazda> <Mercedes>4303</Mercedes> <Mini>3504</Mini> <Mitsubishi>5814</Mitsubishi> </2009> <2010> <Maserati>5</Maserati> <Mazda>2905</Mazda> <Mercedes>2867</Mercedes> <Mini>412</Mini> <Mitsubishi>5284</Mitsubishi> </2010> <2011> <Maserati>4</Maserati> <Mazda>2517</Mazda> <Mercedes>4822</Mercedes> <Mini>552</Mini> <Mitsubishi>6127</Mitsubishi> </2011> </cars>

btw, I generated the json like this:

[php]<?php
$array = [
‘data’ => [
‘cars’ => [
“Maserati”,“Mazda”,“Mercedes”,“Mini”,“Mitsubishi”
],
‘years’ => [
2009 => [0, 2941, 4303, 3504, 5814],
2010 => [5, 2905, 2867, 412, 5284],
2011 => [4, 2517, 4822, 552, 6127]
]
]
];

echo json_encode($array);[/php]ps: must have PHP 5.4+ to use short array syntax, if you are on an older version you have to use the old “$var = array()” markup to make this work

Hello JimL,
Thanks for the response.
Your code works for the josn data of that format.
But if i have json data like { “data”:
[
[“Year”,“Maserati”,“Mazda”,“Mercedes”, “Mini”, “Mitsubhishi”],[“2009”,“25”," 3591",“43”,“4456”, “334”],[“2010”,“33”, “375”, “150”,“45”, “432”]
]}
I would like to get my XML in
2009
25
3591…

For accomplishing the dealer node, I am adding a child to $xml like this
$xmldealer = $xml->addChild(‘dealer’);
But I am not able to get 200925…
I might be missing some basic thing. Please help.

Again, this doesn’t make any sense. Here you have the element dealer, all child items should be the same, but you are mixing year and cars.

Also the json structure is terrible, I changed it for a reason.

Thanks for helping me…

I know the structure is terrible. But, My server programs accept the xml of that structure only…Thats reason for me to manually add dealer node.
I need to have it in this format to get the info of what cars the dealer has sold in that particular year. i am not giving any names because of the company policy.

i get the data from a dealer table that looks like below( its just an example)

year maserati mazda mini mitsubhishi
2009 2 3 4 5
2010 3 4 5 6

Please help…Thanks a ton for your time

Yeah well, it’s not xml so you will just have to loop through the data and echo out whatever data you want.

Thanks for your help… I am planning to echo all the contents in that particular format.
But , As i am new to coding in PHP, COuld you please help me loop through the array and display contents in tags?
year maserati mazda mini mitsubhishi
2009 2 3 4 5
2010 3 4 5 6

I want the output to be 2009
2

here is my code

$fp = fopen("testFile.json", "r");
$inp_info = file_get_contents("testFile.json");
fclose($fp);
echo("$inp_info");
$inp_info = str_replace(array("\t", "\n", "\r"), '', $inp_info);
echo("$inp_info");
$xml_inp_info = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demandSignals>\n</demandSignals>\n");
 //saving generated xml file
 $xml_inp_info->asXML(dirname(__FILE__)."/DemandSignalsFinal.xml") ;
 // function definition to convert array to xml
   foreach($inp_info->data->values as $val) {
      $xml_inp_info->addChild('dealer'> 
      $i = 0;
   foreach ($inp_info->data->info as $key) {
      $xml_inp_info->addChild($key, $val[$i+1]);
      $i++;
   }
    }

I have formatted my json data to output the array like below
{ “data”:{ “info”:[“Year”,“Maserati”,“Mazda”,“Mercedes”,“Mini”,“Mitsubishi”],“values”:{
[" “2009”,
“0”,
“2941”,
“4303”,
“35]4”,
“5814”
],
[
“2010”,
“5”,
“2905”,
“2867”,
“412”,
“5284”
]]}}}

Please help me with this…My str_replace function for carriage return removal is also not working. I will really appreciate if you could help me on this too.
Thanks a ton.

Sponsor our Newsletter | Privacy Policy | Terms of Service