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

查看:274
本文介绍了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然后使用 json_encode

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

问题

网络浏览器收到以下值:

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天全站免登陆