View Full Version : PHP returns invalid XML because of '&'

08-27-2007, 12:05 PM
I'm writing a PHP script to query a database table and return the result as XML. If the result contain the letter '&', the XML is corrupted. How can I fix this problem?
<record id='2' text='jjjj&kkkk'>any</record>

Bill Posters
08-27-2007, 12:10 PM
Encode it as &amp;

Bill Posters
08-27-2007, 12:23 PM
Encode it as &amp; in the stored XML file.


<record id='2' text='jjjj&amp;kkkk'>any</record>

The htmlspecialchars (http://uk.php.net/manual/en/function.htmlspecialchars.php) and htmlentities (http://uk.php.net/manual/en/function.htmlentities.php) won't always do the job properly, so I use my owned, tweaked optionů

function xmlspecialchars($str) {

return str_replace('&#38;#039;','&apos;',htmlspecialchars($str,ENT_QUOTES,'UTF-8'));