note 102452 added to function.json-encode
[email protected] Tue, 15 Feb 2011 16:36:32 -0800
| Newsgroups | php.notes |
|---|---|
| Message-ID | <[email protected]> |
To solve the "problem" with encoded UTF8 chars, is easy:
for example:
$arr = array( 'áéíóúçã', 'áááééé´rŕŕ' );
echo json_encode( $arr );
foreach ($arr as &$a) {
$a = ascii_to_entities( $a );
}
echo json_encode( $arr );
function ascii_to_entities($str)
{
$count = 1;
$out = '';
$temp = array();
for ($i = 0, $s = strlen($str); $i < $s; $i++)
{
$ordinal = ord($str[$i]);
if ($ordinal < 128)
{
if (count($temp) == 1)
{
$out .= '&#'.array_shift($temp).';';
$count = 1;
}
$out .= $str[$i];
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) +
(($temp['1'] % 64) * 64) +
($temp['2'] % 64) : (($temp['0'] % 32) * 64) +
($temp['1'] % 64);
$out .= '&#'.$number.';';
$count = 1;
$temp = array();
}
}
}
return $out;
}
RESULT:
["\u00e1\u00e9\u00ed\u00f3\u00fa\u00e7\u00e3",
"\u00e1\u00e1\u00e1\u00e9\u00e9\u00e9\u00b4r\u0155\u0155"]
Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )
["áéíóúçã","áááééé´rŕŕ"]
Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )
----
Server IP: 69.147.83.197
Probable Submitter: 200.17.33.219
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/102452
Del: integrated -- https://master.php.net/note/delete/102452/integrated
Del: useless -- https://master.php.net/note/delete/102452/useless
Del: bad code -- https://master.php.net/note/delete/102452/bad+code
Del: spam -- https://master.php.net/note/delete/102452/spam
Del: non-english -- https://master.php.net/note/delete/102452/non-english
Del: in docs -- https://master.php.net/note/delete/102452/in+docs
Del: other reasons-- https://master.php.net/note/delete/102452
Reject -- https://master.php.net/note/reject/102452
Search -- https://master.php.net/manage/user-notes.php