Click here to Skip to main content
15,867,765 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following XML string:
XML
<!--?xml version='1.0'?-->
   <catalog>
       <language>
           <name>Php</name>
           <type>Server Side</type>
       </language>
       <language>
           <name>JavaScript</name>
           <type>Client Side</type>
       </language>
	   <language>
           <name>Asp</name>
           <type>Server Side</type>
       </language>
   </catalog>

I need to parse it and convert it into JSON, using PHP.
This is what I tried:
PHP
$xml = simplexml_load_string($xmlData);
foreach ($xml->language as $lang) {
$json[] = [
'name' => $lang->name,
'type' => $lang->type
];
}
var_export(json_encode($json));

Result:
'[{"name":{"0":"Php"},"type":{"0":"Server Side"}},{"name":{"0":"JavaScript"},"type":{"0":"Client Side"}},{"name":{"0":"Asp"},"type":{"0":"Server Side"}}]'

As you can see, the value of each property in an object - while I need this:
'[{"name":"Php","type":"Server Side"},{"name":"JavaScript","type":"Client Side"},{"name":"Asp","type":"Server Side"}]'

What's wrong in my code?

What I have tried:

PHP
$xml = simplexml_load_string($xmlData);
foreach ($xml->language as $lang) {
$json[] = [
'name' => $lang->name,
'type' => $lang->type
];
}
var_export(json_encode($json));
Posted
Updated 10-Apr-23 22:54pm

1 solution

Try:
PHP
$xml = simplexml_load_string($xmlData);
foreach ($xml->language as $lang) {
    $json[] = $lang;
}

var_export(json_encode($json));
Demo[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900