John Davidson

php - converting xml to json does not work when there is CDATA

0 comments
Message:


If I use the following php code to convert an xml to json:



<?php

header("Content-Type:text/json");

$resultXML = "
<QUERY>
<Company>fcsf</Company>
<Details>
fgrtgrthtyfgvb
</Details>
</QUERY>
";

$sxml = simplexml_load_string($resultXML);
echo json_encode($sxml);
?>


I get



{"Company":"fcsf","Details":"\n      fgrtgrthtyfgvb\n   "}


However, If I use CDATA in the Details element as follows:



<?php

header("Content-Type:text/json");

$resultXML = "
<QUERY>
<Company>fcsf</Company>
<Details><![CDATA[
fgrtgrthtyfgvb]]>
</Details>
</QUERY>
";

$sxml = simplexml_load_string($resultXML);
echo json_encode($sxml);


?>



I get the following



{"Company":"fcsf","Details":{}}


In this case the Details element is blank. Any idea why Details is blank and how to correct this?



My Answer:
php
$xmlString = '';
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
echo $json;


The output will be:
json
{"message":"This is a CDATA section"}


As you can see, the CDATA section is not preserved in the JSON output. If you want to preserve the CDATA section, you can use the following code:

php
function xmlToArray($xml) {
$json = json_encode($xml);
$array = json_decode($json, true);
return $array;
}

$xmlString = '';
$xml = simplexml_load_string($xmlString);
$array = xmlToArray($xml);
echo json_encode($array);


This will output:
json
{"message":{"0":"This is a CDATA section"}}


Now the CDATA section is preserved in the JSON output.

Rate this post

3 of 5 based on 5430 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us