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>

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 setAutoCData()), using our extension class: xmlFieldXMLElement:

<?php
$xml = xml_field_load_string('<demo/>');

// Be aware this is a static setting and affects ALL instances.
$xml::setAutoCData(TRUE);

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

CDATA wrap a string

You can wrap a string with cdata by passing it through the static cdata method like this:

$wrapped = xmlFieldXMLElement::cdata('Pizza', TRUE);

This will return:

<![CDATA[Pizza]]>

Obviously there is no need for Pizza to be wrapped, which is why the second argument is set to TRUE. If you omit the second argument (which forces the wrapping), only strings that need it will be wrapped, e.g. <strong>title</strong>.