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. For example:

$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.

Watch a course Learn object oriented PHP

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

$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.