Problems with CDATA in SimpleXML

http://blog.evandavey.com/2008/04/how-to-fix-simplexml-cdata-problem-in-php.html http://stackoverflow.com/questions/2970602/php-how-to-handle-cdata-with-simplexmlelement http://stackoverflow.com/questions/6260224/how-to-write-cdata-using-simplexmlelement

Comparison against SimpleXML

Doesn't print out the cdata correctly

This code snippet:

$xml = simplexml_load_string('<demo/>');
$xml->addChild('cdata', '<![CDATA[<strong>title</strong>]]>');
print $xml->asXml();

Prints this out and transforms the cdata into escaped chars.

<?xml version="1.0"?>
<demo><cdata>&lt;![CDATA[&lt;strong&gt;title&lt;/strong&gt;]]&gt;</cdata></demo>

However the extension class in this module handles this, observe:

$xml = xml_field_load_string('<demo/>');
$xml->addChild('cdata', '<![CDATA[<strong>title</strong>]]>');
print $xml->asXml();

Will yield what you'd expect:

<?xml version="1.0"?>
<demo><cdata><![CDATA[<strong>title</strong>]]></cdata></demo>

Caveat: Accessing the cdata value

If a node has been wrapped in CDATA, that value cannot be accessed directly, e.g. $obj->title, but rather you have to run it through like this $obj->cdata($obj->title).

There is no special handling necessary when you use the $obj->asXml() method.

Automatic CDATA escaping when enabled.

This code snippet:

<?php
$xml = simplexml_load_string('<demo/>');
$xml->addChild('special', '<strong>Do&mdash;Re</strong>');
print $xml->asXml();

Yields the following output:

<?xml version="1.0"?>
<demo><special>&lt;strong&gt;Do&mdash;Re&lt;/strong&gt;</special></demo>

This code snippet (having enabled via autoCData), using our extension class: xmlFieldXMLElement:

<?php
xmlFieldXMLElement::$autoCData = TRUE;
$xml = xml_field_load_string('<demo/>');
$xml->addChild('special', '<strong>Do&mdash;Re</strong>');
print $xml->asXml();

Will automatically wrap values that include the 5 special chars with the CDATA tag:

<?xml version="1.0"?>
<demo><special><![CDATA[<strong>Do&mdash;Re</strong>]]></special></demo>