PHP中json_encode后,在json字符串中依然顯示中文的解決方案


1  <?php
2  header("Content-Type:text/html;charset=utf-8;");
3  $arr = array ('Version_code'=>2,'Version_name'=>'UpdateVersion','Versoin_desc'=>'更新了地圖功能','Versoin_path'=>'http://nnddkj.com/BusIot/APK/BusIot.apk');
4  echo json_encode($arr);
5  ?>

 

如上代碼,即為將字符串變量轉化成json格式輸出,但是輸出結果如下:

{"Version_code":2,"Version_name":"UpdateVersion","Versoin_desc":"\u66f4\u65b0\u4e86\u5730\u56fe\u529f\u80fd","Versoin_path":"http:\/\/nnddkj.com\/BusIot\/APK\/BusIot.apk"}

 

即數組中所有中文在json_encode之后都不見了或者出現\u2353等。

解決方法是用urlencode()函數處理以下,在json_encode之前,把所有數組內所有內容都用urlencode()處理一下,然用json_encode()轉換成json字符串,最后再用urldecode()將編碼過的中文轉回來。

1 <?php
2 header("Content-Type:text/html;charset=utf-8;");
3 $arr = array ('Version_code'=>2,'Version_name'=>'UpdateVersion','Versoin_desc'=>urlencode('更新了地圖功能'),'Versoin_path'=>urlencode('http://nnddkj.com/BusIot/APK/BusIot.apk'));
4 echo urldecode(json_encode($arr));
5 ?>

輸出結果:{"Version_code":2,"Version_name":"UpdateVersion","Versoin_desc":"更新了地圖功能","Versoin_path":"http://nnddkj.com/BusIot/APK/BusIot.apk"}

搞定。。

 

附:json_decode對JSON格式的字符串進行編碼,而json_encode對變量進行 JSON 編碼

json_decode - 對JSON 格式的字符串進行編碼

說明:
mixed json_decode ( string $json [, bool $assoc ] )
接受一個 JSON 格式的字符串並且把它轉換為 PHP 變量 ,$assoc,當該參數為 TRUE 時,將返回 array 而非 object

json_encode:詳細問度娘

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM