PHP5.2,对包含中文的数组作json处理,用json_encode函数后,显示乱码。
解决思路:
数组中值先作urlencode处理,再作json_encode处理,最后再作urldecode处理。
实例:
<?php
$data = array(
‘game’ => ‘冰火国度’,
‘name’ => ‘刺之灵’,
‘country’ => ‘冰霜国’,
‘level’ => 45
);
echo json_encode( $data );
echo ‘<br>’;
/**
* 处理json_encode乱码
*/
$newData = array();
foreach( $data as $key => $value )
{
$newData[ $key ] = urlencode( $value );
}
echo urldecode( json_encode( $newData ) );
?>
结果显示:
{“game”:”\u51b0\u706b\u56fd\u5ea6″,”name”:”\u523a\u4e4b\u7075″,”country”:”\u51b0\u971c\u56fd”,”level”:45}
{“game”:”冰火国度”,”name”:”刺之灵”,”country”:”冰霜国”,”level”:”45″}
{“game”:”冰火国度”,”name”:”刺之灵”,”country”:”冰霜国”,”level”:”45″}