Quest

我希望获取带有重音字符的行.列(NAME)的编码是latin1_swedish_ci.

The Code

The following query returns Abord â Plouffe using phpMyAdmin:

SELECT C.NAME FROM CITY C
WHERE C.REGION_ID=10 AND C.NAME_LOWERCASE LIKE '%abor%'
ORDER BY C.NAME LIMIT 30

The following displays expected values (function is called db_fetch_all( $result )):

  while( $row = mysql_fetch_assoc( $result ) ) {
    foreach( $row as $value ) {
      echo $value . " ";
      $value = utf8_encode( $value );
      echo $value . " ";
    }

    $r[] = $row;
  }

The displayed values: 5482 5482 Abord â Plouffe Abord â Plouffe

然后使用json_encode对该数组进行编码:

$rows = db_fetch_all( $result );
echo json_encode( $rows );

Problem

Web浏览器接收下列值:

{"ID":"5482","NAME":null}

而不是:

{"ID":"5482","NAME":"Abord â Plouffe"}

(或编码的等效物.)

Question

The documentation states that json_encode() works on UTF-8. I can see the values being encoded from LATIN1 to UTF-8. After the call to json_encode(), however, the value becomes null.

How do I make json_encode() encode the UTF-8 values properly?

一种可能的解决方案是使用Zend Framework美元,但如果可以避免的话,我宁愿不使用.

推荐答案

// Create an empty array for the encoded resultset
$rows = array();

// Loop over the db resultset and put encoded values into $rows
while($row = mysql_fetch_assoc($result)) {
  $rows[] = array_map('utf8_encode', $row);
}

// Output $rows
echo json_encode($rows);

Json相关问答推荐

JoltChange:将输入数组的每个对象拆分为2个独立的对象,并将其放入输出数组中

使用Powershell脚本将配置信息块添加到json文件

如何在JQ过滤器文件中使用多行?

Terraform迭代JSON文件以获取键值对

如何将复杂的 JSON 反序列化为 Rust 类型?

使用杰克逊解析Kotlin 中的通用密封类

Powershell 7.2:ConvertFrom-Json - 日期处理

JSON 字段的多个名称

jq:来自嵌套 JSON 的映射

jq:用列表包装所有第一级原子值

Servicestack 返回数组而不是带有数组的对象

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

为什么在我们有 json_encode 时使用 CJSON 编码

一起使用 Argparse 和 Json

在 JSON 字符串中react i18n 换行符

在 JavaScript 中从 Json 数据中删除反斜杠

将 PHP 结果数组转换为 JSON

jQuery fullcalendar 发送自定义参数并使用 JSON 刷新日历

你如何在 Arrays of Arrays 上 OPENJSON

使用新的 Net Core 3.0 Json 时忽略属性