php中json_encode處理gbk與gb2312中文亂碼問題的解決方案,_PHP教程

來源:互聯網
上載者:User

php中json_encode處理gbk與gb2312中文亂碼問題的解決方案,


本文講述了php中json_encode處理gbk與gb2312中文亂碼問題的解決方案,具體方法如下:

1.json_encode()中文在gbk/gb2312中對中文返回為null

$arr = array (  array (    'catid' => '4',    'catname' => 'www.jb51.net',    'meta_title' => '幫客之家'   )); echo json_encode($arr);

運行結果:

[{"catid":"4","catname":"www.jb51.net","meta_title":null}]

  看一了嗎"meta_title":null 他本來是有一個值的為"幫客之家"了,這個我們查了一下原理是json_encode只支援uft-8編碼,我們轉換一下

<?php$data="JSON中文";$newData=iconv("GB2312″,"UTF-8//IGNORE",$data);echo $newData;//ignore的意思是忽略轉換時的錯誤,如果沒有ignore參數,所有該字元後面的字元都不會被儲存。//或是("GB2312″,"UTF-8″,$data);?>

2.後台PHP頁面(頁面編碼為UTF-8或者已經把字元轉為UTF-8)使用json_encode將PHP中的array數組轉為JSON字串。例如:

<?php$testJSON=array('name'=>'中文字串','value'=>'test');echo json_encode($testJSON);?>

查看輸出結果為:

{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}

  可見即使用UTF8編碼的字元,使用json_encode也出現了中文亂碼。解決辦法是在使用json_encode之前把字元用函數urlencode()處理一下,然後再json_encode,輸出結果的時候再用函數urldecode()轉回來。具體如下:

<?php$testJSON=array('name'=>'中文字串','value'=>'test');//echo json_encode($testJSON);foreach ( $testJSON as $key => $value ) {$testJSON[$key] = urlencode ( $value );}echo urldecode ( json_encode ( $testJSON ) );?>

查看輸出結果為:

{"name":"中文字串","value":"test"}

  總結:json_encode函數只能處理uft8字串,如果是中文估計是對位元組處理不好,因為中文gbk與uft長度是不一樣的,這個也不做深入介紹了。




http://www.bkjia.com/PHPjc/840739.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/840739.htmlTechArticlephp中json_encode處理gbk與gb2312中文亂碼問題的解決方案, 本文講述了php中json_encode處理gbk與gb2312中文亂碼問題的解決方案,具體方法如下:...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.