UTF-8 字符编码之战 json_encode() [英] UTF-8 character encoding battles json_encode()

查看:33
本文介绍了UTF-8 字符编码之战 json_encode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务

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

I am looking to fetch rows that have accented characters. The encoding for the column (NAME) is latin1_swedish_ci.

代码

以下查询使用 phpMyAdmin 返回 Abord â Plouffe:

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

以下显示预期值(函数名为db_fetch_all( $result )):

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;
  }

显示值:5482 5482 Abord â Plouffe Abord ¢ Plouffe

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

The array is then encoded using json_encode:

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

问题

Web 浏览器接收以下值:

The web browser receives the following value:

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

代替:

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

(或编码的等价物.)

问题

文档说明 json_encode() 适用于 UTF-8.我可以看到值从 LATIN1 编码为 UTF-8.但是,在调用 json_encode() 之后,该值变为 null.

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.

如何让 json_encode() 正确编码 UTF-8 值?

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

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

One possible solution is to use the Zend Framework, but I'd rather not if it can be avoided.

推荐答案

// 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);

这篇关于UTF-8 字符编码之战 json_encode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆