Make user input safe for XML

character-encoding, php, xml

Solution

Wrap information in `CDATA` tags and encode data with `htmlentities()`

'<tag><![CDATA[' . htmlentities($theData) . ']]></tag>'

Or using DOM

$dom = new DOMDocument("1.0", "utf-8");

/* ... */

$dom->createCDATASection(htmlentities($theData));

Problem

What is the best practice for generating valid XML with PHP from user submitted text, e.g. eCommerce sales data with ampersands, angle brackets, non-ascii accent characters, new lines etc etc. What functions, libraries, regexes do folks rely on?

Original source