本文實例講述了PHP實現json_decode不轉義中文的方法。分享給大家供大家參考,具體如下:
默認情況下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) { //convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding 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'); }
PS:這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.jb51.net/code/jsoncodeformat
C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP中json格式數據操作技巧匯總》、《PHP數學運算技巧總結》、《PHP基本語法入門教程》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。