PHP-json_encode中文亂碼

餘二五發表於2017-11-14

呼叫json_encode()函式將JSON物件轉換為字串, 如果其中包含有中文,預設會輸出為unicode編碼,如u8023

解決方案1

升級到PHP 5.4,在json_encode()函式中,第二個引數指定JSON_UNESCAPED_UNICODE即可。

解決方案2

對於低版本PHP,對unicode碼再進行解碼,解碼函式如下:

function decodeUnicode($str)

{

    return preg_replace_callback(`/\\u([0-9a-f]{4})/i`,

        create_function(

            `$matches`,

            `return mb_convert_encoding(pack(“H*”, $matches[1]), “UTF-8”, “UCS-2BE”);`

        ),

        $str);

}

 

例子如下:

$arr = array(`name1`:”中文“,`name2`:`abc12`);

$jsonstr = decodeUnicode(json_encode($arr));

本文轉自 tywali 51CTO部落格,原文連結:http://blog.51cto.com/lancelot/1783626,如需轉載請自行聯絡原作者


相關文章