Search code examples
phpjsonxmlcdatasimplexml

XML to JSON when there is <![CDATA[]]> in PHP


I am trying to convert a group of xml files from a directory to json format but in my xml there are CDATA, son when it converts the CDATA went empty. I was using simplexml_load_file($xml) but I read that doesn't get CDDATA, so i tried simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA) but

It just gave me this errors:

Warning: simplexml_load_string(): Entity: line 5: parser error : Start tag expected, '<' not found in C:\xampp\htdocs\xmlfilter\xmlfilter.php on line 65

Warning: simplexml_load_string(): in C:\xampp\htdocs\xmlfilter\xmlfilter.php on line 65

Warning: simplexml_load_string(): ^ in C:\xampp\htdocs\xmlfilter\xmlfilter.php on line 65

At the end of the new file it write 'false?¿':

"LETRA_IMPRENTA":{},"LETRA_MAYUSCULA":{},"PANTALLA_VERTICAL":{},"PANTALLA_PEQUENA":{},"NAVEGADOR_CHROME":{},"SALIR_MITAD_BODY":{},"SALIR_MITAD_GUARDAR":{},"SALIR_MITAD_NOGUARDAR":{}}}falsefalsefalsefalsefalsefalsefalsefalse

Example of my xml:

<LANGUAGE><HELLO><![CDATA[hello]]></HELLO></LANGUAGE>

That's it my code: enter image description here


Solution

  • $xml = simplexml_load_file("xml/".$y);
    simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)
    

    simplexml_load_file takes a file path in a string as input and returns a simple XML object. This is fine.

    simplexml_load_string takes some XML in a string as input and returns a simple XML object. You are giving it a simple XML object as input, not a string. This is not fine.

    Use simplexml_load_file or simplexml_load_string, not both.