PHP conversion of xml to json does not work when there is CDATA

If I use the following code phpto convert xmlto 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 CDATAin an element Detailsas 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 item is Detailsempty. Any idea why it is Detailsempty and how to fix it?

+4
source share
1 answer

This is not a JSON encoding problem - it var_dump($sxml->Details)shows that SimpleXML has already mixed it up, since you only get

object(SimpleXMLElement)#2 (0) {
}

- "empty" SimpleXMLElement, the contents of CDATA are already missing.

, (, , ), googling "simplexml cdata" SimpleXML-, :

CDATA simplexml, str_replace/preg_replace CDATA simplexml.

, CDATA .

$xml = simplexml_load_file($xmlfile, 'SimpleXMLElement', LIBXML_NOCDATA);

,

$sxml = simplexml_load_string($resultXML, 'SimpleXMLElement', LIBXML_NOCDATA);

,

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

JSON.

+20

Source: https://habr.com/ru/post/1525183/


All Articles