首页 > 解决方案 > PHP json_encode 和 utf8_encode 不适用于我的 php 文件

问题描述

我有一些需要编码的 json - 越南语单词。我尝试使用 JSON_UNESCAPED_UNICODE 但看起来它不再工作了。

  header("Content-type: application/json; charset=utf-8");
  $db = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_errno());
  $result = mysqli_query($db,"SELECT * FROM categories") ;
  if (mysqli_num_rows($result) > 0) {
    $response["categories"] = array();
    while ($row = mysqli_fetch_array($result)) {
       $categories["id"] = json_encode($row["id"]);
       $categories["name"]= json_encode($row["name"],JSON_UNESCAPED_UNICODE);
       array_push($response["categories"], $categories);
    }
    $response["result"] = "OK";
    $myJSON = json_encode($response);
    echo $myJSON;
  }

输入:

id=1 name=Truyện Cổ Tích

输出:

id = 1 名称 = 假

这是我第一次尝试 PHP。我的 php 版本是 7.2.8。

标签: phpjson

解决方案


  1. 第一次运行mysqli_query('SET NAMES utf8')
  2. 打印错误信息json_last_error()

推荐阅读