note 97486 deleted from function.htmlentities by danbrown
| From: | danbrown@php.net | Date: | Thu, 22 Apr 2010 14:08:15 +0000 |
| Subject: | note 97486 deleted from function.htmlentities by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168508@lists.php.net to get a copy of this message | ||
Note Submitter: tal at talater dot com
----
We've adapted the excellent function provided by silverbeat, so that it also encodes two-byte
characters. This made it safer for the output to be used in XML (which previously choked on output
like £ which the original function put out).
/**
* Encodes a string for use in XML
*
* @param string $string
* @param boolean $encodeTags=true
* @return string
*/
function xml_character_encode($string, $encodeTags=true) {
$string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
$result = '';
for ($i = 0; $i < strlen($string); $i++) {
$char = $string[$i];
$ascii = ord($char);
if ($ascii < 128) {
// one-byte character
$result .= ($encodeTags) ? htmlentities($char) : $char;
} else if ($ascii < 192) {
// non-utf8 character or not a start byte
} else if ($ascii < 224) {
// two-byte character
$ascii1 = ord($string[$i+1]);
$unicode = (63 & $ascii) * 64 +
(63 & $ascii1);
$result .= "&#$unicode;";
$i++;
} else if ($ascii < 240) {
// three-byte character
$ascii1 = ord($string[$i+1]);
$ascii2 = ord($string[$i+2]);
$unicode = (15 & $ascii) * 4096 +
(63 & $ascii1) * 64 +
(63 & $ascii2);
$result .= "&#$unicode;";
$i += 2;
} else if ($ascii < 248) {
// four-byte character
$ascii1 = ord($string[$i+1]);
$ascii2 = ord($string[$i+2]);
$ascii3 = ord($string[$i+3]);
$unicode = (15 & $ascii) * 262144 +
(63 & $ascii1) * 4096 +
(63 & $ascii2) * 64 +
(63 & $ascii3);
$result .= "&#$unicode;";
$i += 3;
}
}
return $result;
}