note 102452 modified in function.json-encode by danbrown

[email protected] Wed, 16 Feb 2011 05:56:39 -0800
Newsgroups php.notes
Message-ID <[email protected]>
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