W3docs

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You can use the addCData() method of the SimpleXMLElement class to add a CDATA section to an XML element.

You can use the addCData() method of the SimpleXMLElement class to add a CDATA section to an XML element. For example:

Example of using the addCData() method of the SimpleXMLElement class to add a CDATA section to an XML element in PHP

$xml = new SimpleXMLElement('<root/>');
$xml->addChild('example')->addCData('<![CDATA[This is some example text]]>');

This will add a child element to the $xml element called "example" containing the string "This is some example text" wrapped in a CDATA section.

Alternatively, you can also use the CDATA property to add a CDATA section to an XML element.

Example of using the CDATA property to add a CDATA section to an XML element in PHP

$xml = new SimpleXMLElement('<root/>');
$xml->example = '<![CDATA[This is some example text]]>';

This will also add the same child element containing the same CDATA section.


$xml->asXML();

This will return the XML as string which you can save or print to the browser.