json_encode轉義中文問題


默認情況下php的 json_decode 方法會把特殊字符進行轉義,還會把中文轉為Unicode編碼形式。

這使得數據庫查看文本變得很麻煩。所以我們需要限制對於中文的轉義。

對於PHP5.4+版本,json_decode函數第二個參數,可以用來限制轉義范圍。

要限制中文,使用JSON_UNESCAPED_UNICODE參數。

      json_encode($a, JSON_UNESCAPED_UNICODE); 

例如:在保存數組中中文對應的分數時,其中包含有中文,在將數組轉換成字符串json_encode()時,加入參數 

JSON_UNESCAPED_UNICODE,就可以防止中文數據被轉義。
        $answer_score[0] = array("中文1" => mt_rand(95,99));//中文名稱對應的分數
        $answer_score[1] = array("中文2" => mt_rand(81,87));
        $answer_score[2] = array("中文3" => mt_rand(70,80));
        $answer_score[3] = array("中文4" => mt_rand(70,80));
        $answer_score[4] = array("中文5" => mt_rand(70,80));
        $json_answer_score = (json_encode($answer_score , JSON_UNESCAPED_UNICODE));
        $model = new SweepstakesModel();
        $selfAnswer = $model->updateGroupxzSelfanswer("pengjun123" , "werwef" , $json_answer_score , "軍軍");

 在數據庫中存儲的結果如下:

Array
(
    [id] => 1
    [openid] => pengjun123
    [nickname] => 彭軍
    [icon] => http://wx.qlogo.cn/mmopen/qhDbvnE5DMn5stSjg52mmB4Tj1nMVCticRShFfBriaE8lAsF3cgzNtZGogVJXUyUOG1W6hQKFWBM8SZhEnIrTyb8LO1nc6sgQd/0
    [answer] => werwef
    [addtime] => 2017-08-15 18:24:22
    [subtime] => 2017-08-28 12:13:58
    [answer_score] => [{"中文1":95},{"中文2":82},{"中文3":72},{"中文4":76},{"中文5":70}]
    [answer_point] => 軍軍
    [extend] => 1
    [help_answer_score] => 
    [helppositionName] => 
)

如果不使用 JSON_UNESCAPED_UNICODE , 則會出現如下的轉義效果

Array
(
    [id] => 1
    [openid] => pengjun123
    [nickname] => 彭軍
    [icon] => http://wx.qlogo.cn/mmopen/qhDbvnE5DMn5stSjg52mmB4Tj1nMVCticRShFfBriaE8lAsF3cgzNtZGogVJXUyUOG1W6hQKFWBM8SZhEnIrTyb8LO1nc6sgQd/0
    [answer] => werwef
    [addtime] => 2017-08-15 18:24:22
    [subtime] => 2017-08-28 12:21:19
    [answer_score] => [{"\u4e2d\u65871":98},{"\u4e2d\u65872":87},{"\u4e2d\u65873":77},{"\u4e2d\u65874":79},{"\u4e2d\u65875":78}]
    [answer_point] => 軍軍
    [extend] => 1
    [help_answer_score] => 
    [helppositionName] => 
)

這種轉義之后的數據在數據庫很難閱讀

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM