Monday, February 13, 2006

Handle special ASCII characters in PHP and HTML

I had today the following situation: A html site sends an httpRequest using Ajax to a php script that returns an html table representing the result set. Unfortunately, the mysql result set contains ASCII characters with a code between 0 and 32. Since I parse the responseText of the xmlHttpRequest as an xml document, the resulted xml is invalid because of the existence of those characters.
To solve this problem, I wrote the following php function that replaces any ASCII character that may affect the validation of the xml file with its identifier.
function convertSpecialAscii($str){
$tab = array('NUL','SOH','STX','ETX',
'EOT','ENQ','ACK', 'BEL',
'BS','HT (\t)','LF (\n)',
'VT','FF';'CR (\r)',
'SO', 'SI', 'DLE', 'DC1',
'DC2', 'DC3',
'DC4', 'NAK', 'SYN', 'ETB',
'CAN', 'EM', 'SUB', 'ESC',
'FS', 'GS', 'RSD', 'US');
$tempStr = '<font color="red"/>[' . $tab[$i]. ']</font>';
$str = str_replace(chr($i) ,$tempStr, $str);
return $str;

The code is based on an example from


Post a Comment

<< Home