默認情況下php的 json_decode 方法會把特殊字符進行轉義,還會把中文轉為Unicode編碼形式。
這使得數據庫查看文本變得很麻煩。所以我們需要限制對於中文的轉義。
對於PHP5.4+版本,json_decode函數第二個參數,可以用來限制轉義范圍。
要限制中文,使用JSON_UNESCAPED_UNICODE參數。
json_encode($a, JSON_UNESCAPED_UNICODE);
對於PHP5.3版本,可以先把ASCII 127以上的字符轉換為HTML數值,這樣避免被json_decode函數轉碼
function my_json_encode($arr)
{
array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); });
return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');
}