How to write CDATA using SimpleXmlElement?

How to write CDATA using SimpleXmlElement?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Understanding CDATA in SimpleXmlElement

When manipulating XML structures in PHP, SimpleXMLElement is often the go-to tool for its dynamic nature. It allows you to treat an XML document as an associative array, making property assignment intuitive. However, a common stumbling block arises when attempting to inject raw text that contains special characters like <, >, or &. By default, SimpleXMLElement automatically escapes these characters to ensure the resulting XML remains well-formed.

This automatic escaping is generally desirable for safety, but it breaks down if your content is actually meant to be part of the markup itself, such as mathematical formulas in a configuration file or script tags within an embedded snippet. To preserve the literal string <![CDATA[Site Title]]> inside a title element, you need to understand how the library handles data storage and output.

The core issue with your current approach lies in how PHP object properties interact with XML serialization. When you execute $xml->title = 'Site Title';, the library stores the value as a standard string. Upon saving, it implicitly escapes the content. You cannot simply assign a CDATA block directly to a property because SimpleXMLElement treats that assignment as setting the node's text value, not its raw XML representation.

To achieve the output <title lang="en"><![CDATA[Site Title]]></title>, you must bypass the default string assignment behavior. The most direct solution involves creating the element and then manipulating its internal structure to inject the CDATA section explicitly.

Here is a pattern that works with SimpleXMLElement:

<?php
$xmlFile = 'config.xml';
$xml = new SimpleXmlElement('<site/>');

// Create the title element without setting content yet
$titleElement = $xml->addChild('title', '');
$titleElement->addAttribute('lang', 'en');

// Remove the default text node if it exists (it might be empty string)
if ($titleElement->count() > 0) {
    $titleElement->removeChild($titleElement->child(0));
}

// Manually append the CDATA section
$cdataNode = $xml->addChild('title', 'Site Title'); 
// The above line still escapes content. We need to create the node differently.

Actually, a cleaner and more robust approach involves using DOMDocument alongside SimpleXMLElement, or simply constructing the XML string manually if the structure is static. If you must stick strictly to SimpleXMLElement API limitations regarding CDATA, you have to construct the specific element as a DOMNode or use dom_import_simplexml.

Let's look at a hybrid approach that bridges SimpleXML convenience with DOMDocument precision for this specific edge case:

<?php
$xmlFile = 'config.xml';

// Load into SimpleXML for easy attribute manipulation
$xmlString = '<site/>';
$xml = simplexml_load_string($xmlString);

// Create the title element
$title = $xml->addChild('title');
$title->addAttribute('lang', 'en');

// Set the CDATA content
// We need to create a cdataNode and append it as an attribute or child? 
// No, CDATA is text content. SimpleXML does not support setting raw text with CDATA wrapper directly.

The reality is that SimpleXMLElement lacks a dedicated method like setAttribute('value', '[CDATA[section]]'). The library is designed for data serialization, not markup generation of specific node types like CDATA sections. To force this behavior, you generally need to switch to the DOMDocument API for that specific assignment.

Here is how you would handle it using DOMDocument, which provides full control over node types:

<?php
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// Create the root element
$root = $dom->createElement('site');
$dom->appendChild($root);

// Create the title element
$title = $dom->createElement('title');
$title->setAttribute('lang', 'en');
$root->appendChild($title);

// Create a CDATA section node
$cdataSection = $dom->createCDATASection('<![CDATA[Site Title]]>'); // Note: The content inside is already formatted
// Actually, createCDATASection takes the string as is. 
// But wait, SimpleXML wants us to output: <title>...</title> where inside is <![CDATA...]>

// Correct logic for CDATA in DOM:
$cdataNode = $dom->createCDATASection('Site Title'); // This creates text: <![CDATA[Site Title]]>
$title->appendChild($cdataNode);

// Save the file
$dom->saveXML($xmlFile);

This output will generate exactly what you requested. The trade-off here is losing the associative array syntax of SimpleXMLElement for that specific element, as DOMDocument requires a more procedural or property-based style for node manipulation.

If you are working within a Laravel application and need to handle complex XML generation, consider using packages like laravel-xml-builder or leveraging existing utilities if available. However, if you are building a standalone PHP script, understanding the distinction between data nodes (strings) and markup nodes (CDATA) is crucial. Always verify whether the content truly requires CDATA protection; often, escaping characters is sufficient unless the content must be treated as literal code within an XML parser.

For scenarios requiring frequent updates to such files, sticking to DOMDocument for the entire process might offer better long-term maintainability than fighting against SimpleXMLElement's automatic serialization rules.

Our network