Got it! I adapted the code from this great solution (archived version):
<?php
// http://coffeerings.posterous.com/php-simplexml-and-cdata
// https://web.archive.org/web/20110223233311/http://coffeerings.posterous.com/php-simplexml-and-cdata
// Customized 'SimpleXMLElement' class.
class SimpleXMLExtended extends SimpleXMLElement {
// Create CDATA section custom function.
public function addCData( $cdata_text ) {
$node = dom_import_simplexml( $this );
$ownerDocumentNode = $node->ownerDocument;
$node->appendChild( $ownerDocumentNode->createCDATASection( $cdata_text ));
}
}
// How to create the following example, below:
// <?xml version="1.0"?>
// <site>
// <title lang="en"><![CDATA[Site Title]]></title>
// </site>
/*
* Instead of SimpleXMLElement:
* $xml = new SimpleXMLElement( '<site/>' );
* create from custom class, in this case, SimpleXMLExtended.
*/
// Name of the XML file.
$xmlFile = 'config.xml';
// <?xml version="1.0"?>
// <site></site>
// ^^^^^^^^^^^^^
$xml = new SimpleXMLExtended( '<site/>' );
// Insert '<title><title>' into '<site></site>'.
// <?xml version="1.0"?>
// <site>
// <title></title>
// ^^^^^^^^^^^^^^^
// </site>
$xml->title = NULL; // VERY IMPORTANT! We need a node where to append.
// CDATA section custom function.
// <?xml version="1.0"?>
// <site></site>
// <title><![CDATA[Site Title]]></title>
// ^^^^^^^^^^^^^^^^^^^^^^
// </site>
$xml->title->addCData( 'Site Title' );
// Add an attribute.
// <?xml version="1.0"?>
// <site></site>
// <title lang="en"><![CDATA[Site Title]]></title>
// ^^^^^^^^^^
// </site>
$xml->title->addAttribute( 'lang', 'en' );
// Save.
$xml->saveXML( $xmlFile );
?>
XML file, config.xml
, generated:
<?xml version="1.0"?>
<site>
<title lang="en"><![CDATA[Site Title]]></title>
</site>
Thank you Petah, hope it helps!
<title lang="en">Site Title</title>
and<title lang="en"><![CDATA[Site Title]]></title>
are identical except that one uses more bytes and is harder to read as a human. – Ackerman<title lang="en">Site<br>Title</title>
it would break the XML parser (opening br tag without a closing is not strict XML) whereas<title lang="en"><![CDATA[Site<br>Title]]></title>
does not. So when dealing with clients it's often more readable to just have CDATA as opposed to all the wonky escaping said non-CDATA node may have to contain to avoid CDATA. – Oedipus<em></em>
tag escaped within the content would add as many bytes as the surrounding CDATA tags. You see, there are MANY cases where CDATA is a viable solution, whether hand or code populated XML. – Oedipus