1.json_encode()中文在gbk/gb2312中對中文返回為null
$arr = array (?
?array (?
? ?'catid' => '4',?
? ?'catname' => 'www.genban.org',?
? ?'meta_title' => 'genban'?
? )
);
echo json_encode($arr);
運行結果:
[{"catid":"4","catname":"www.genban.org","meta_title":null}]
看一了嗎"meta_title":null 他本來是有一個值的為"genban"了,這個我們查了一下原理是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長度是不一樣的,這個也不做深入介紹了。【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!