json encode 中文解決方法

2021-05-10 10:04:33 字數 1232 閱讀 6264

**自:http://www.phpyu.cn/view/index.php/id_224.html

json 是乙個很好的資料結構現在已經廣泛用在網路資料傳輸上

php 自身待了兩個和json 相關的函式

json_encode  和 json_decode

這兩個函式的具體用法 網上有很多相關的文章

本文主要介紹 用json_encode 時 中文無法轉換的解決方案

本文假設 檔案所用的編碼為gb2312;

先寫出所需的陣列

<?php

$json 

= array (

0  => 

array (

'id' 

=> 

'13'

, 'name' 

=> 

'桌球'

, ),

1  => 

array (

'id' 

=> 

'17'

, 'name' 

=> 

'籃球'

, )

) ?>

如果直接用函式json_encode

<?php

echo 

json_encode

($json

); ?>

結果為:

<?php

[,]

?>

可以看到漢字沒有被轉義  都為null

這是因為json僅僅轉義encoding編碼

故上面語句應該先轉換編碼

<?php

foreach (

$ajax 

as $key

=>

$val

) echo 

json_encode

($json

); ?>

客戶端js**

用上面的**js會報錯 說編碼不符合標準

原因是因為js 中decodeuri 僅僅支援utf8 轉碼 

所以 

php

**應該為下面的**

<?php

foreach (

$ajax 

as $key

=>

$val

) echo 

json_encode

($json

); ?>

解決 json encode 中文亂碼

解決以下問題 json encode 中文後的字串不可閱讀 json encode 多級陣列中文亂碼問題 json encode 陣列中包含換行時錯誤問題 json encode 陣列中鍵為中文的問題 php function encode arr return addcslashes urldec...

json encode 中文解決方法

json 是乙個很好的資料結構現在已經廣泛用在網路資料傳輸上 php 自身待了兩個和json 相關的函式 json encode 和 json decode 這兩個函式的具體用法 網上有很多相關的文章 本文主要介紹 用json encode 時 中文無法轉換的解決方案 本文假設 檔案所用的編碼為gb...

php 解決json encode中文問題

眾所周知使用json encode可以方便快捷地將物件進行json編碼,但是如果物件的屬性中存在著中文,問題也就隨之而來了。json encode會將中文轉換為unicode編碼 例如 胥 經過json encode處理後變為 u80e5 最終的json中中文部分被替換為unicode編碼。我們要解...