note 102452 modified in function.json-encode by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Feb 2011 13:56:39 +0000 |
| Subject: | note 102452 modified in function.json-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-177028@lists.php.net to get a copy of this message | ||
To solve the "problem" with encoded UTF8 chars, is easy:
for example:
<?php
$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ÅÅ )
--was--
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ÅÅ )
http://php.net/manual/en/function.json-encode.php