php自帶了json_encode來處理json數(shù)據(jù),那么它們對(duì)中文的支持不好,下面我們來看個(gè)實(shí)例:
echo json_encode(array(123213,'中文'));
{"platformid":"123213","userid":"1023","username":"u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc"}
我們會(huì)發(fā)現(xiàn),英文可以正確解析,但中文就出來:
u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc,這可能是unicode編碼,但我沒測試過只是自己猜的。下面我們來看一款解決json中文亂碼的函數(shù)
- private function to_utf8($in)
- {
- if (is_array($in)) {
- foreach ($in as $key => $value)
- {
- $out[$this->to_utf8($key)] = $this->to_utf8($value);
- }
- }
- elseif(is_string($in))
- {
- if(mb_detect_encoding()($in) != "utf-8")
- return utf8_encode($in);
- else
- return $in;
- }
- else
- {
- return $in;
- }
- return $out;
- }
1.把$usr->username直接輸出,頁面頭設(shè)置charset=utf-8.亂碼
2.echo json_encode($usr)輸出username=null
3.頁面頭設(shè)置為charset=gbk,輸出正確->可以確定原編碼為gbk
最后通過ie,chrome,firefox測試得出結(jié)論:
1.保證頁面字符集與數(shù)據(jù)庫一致,輸出一定正常.
2.做json_encode時(shí)保證數(shù)據(jù)編碼是utf-8,json_decode正常.
3.如果要對(duì)非utf-8字符做json_encode,先轉(zhuǎn)換成utf-8.
4.對(duì)非utf-8字符做json_decode的時(shí)候,千萬不能忘記轉(zhuǎn)換成原先的編碼,否則會(huì)輸出亂碼!
新聞熱點(diǎn)
疑難解答