PHP5.4开始 json对中文的支持

  1. <?php
  2. $code = 220;
  3. $message = '测试游戏啊!';
  4. $data = [1, 2, 3, 3, 4, 4, 7];
  5. $test_data = ['code' => $code, 'message' => $message, 'data' => $data];
  6. $test_0 = json_encode($test_data);
  7. $test_1 = json_encode($test_data, JSON_UNESCAPED_UNICODE);
  8. $test_2 = json_encode($test_data, JSON_PRETTY_PRINT);
  9. $test_3 = json_encode($test_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  10. echo "<pre>";
  11. print_r($test_0);
  12. echo '<hr>';
  13. print_r($test_1);
  14. echo '<hr>';
  15. print_r($test_2);
  16. echo '<hr>';
  17. print_r($test_3);
  18. echo "</pre>";
  19. exit;

json_encode不转义斜线,不转义中文: - 图1

json_encode不转义斜线,不转义中文:

  1. json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

由于 json_encode 和 json_decode只支持utf-8编码的字符,GBK的字符要用json就得转换一下,附自己写的GBK转UTF-8的代码:

  1. /*
  2. 字符串GBK转码为UTF-8,数字转换为数字。
  3. */
  4. function ct2($s){
  5. if(is_numeric($s)) {
  6. return intval($s);
  7. } else {
  8. return iconv("GBK","UTF-8",$s);
  9. }
  10. }
  11. /*
  12. 批量处理gbk->utf-8
  13. */
  14. function icon_to_utf8($s) {
  15. if(is_array($s)) {
  16. foreach($s as $key => $val) {
  17. $s[$key] = icon_to_utf8($val);
  18. }
  19. } else {
  20. $s = ct2($s);
  21. }
  22. return $s;
  23. }
  24. echo json_encode(icon_to_utf8("厦门"));