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
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><![CDATA[<strong>title</strong>]]></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>
This code snippet:
<?php
$xml = simplexml_load_string('<demo/>');
$xml->addChild('special', '<strong>Do—Re</strong>');
print $xml->asXml();
Yields the following output:
<?xml version="1.0"?>
<demo><special><strong>Do—Re</strong></special></demo>
This code snippet (having enabled via autoCData
), using our extension class: xmlFieldXMLElement
:
<?php
$xml = xml_field_load_string('<demo/>');
// Be aware this is a static setting and affects ALL instances.
$xml::setConfig('autoCData', TRUE);
$xml->addChild('special', '<strong>Do—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—Re</strong>]]></special></demo>
Be aware that this is a setting for all instances and should be disabled after use, unless you intend for a constant on.
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>
.