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

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

问题描述

任务

我期待获取已重音符号的字符行。该列(名称)的 latin1_swedish_ci

编码

的code

下面的查询将返回 Abordâ普劳夫使用phpMyAdmin:

  SELECT C.NAME从C城
WHERE C.REGION_ID = 10,C.NAME_LOWERCASE LIKE'%ABOR%
ORDER BY C.NAME LIMIT 30
 

下面显示预期值(函数被调用 db_fetch_all($结果)):

 而($行= mysql_fetch_assoc($结果)){
    的foreach($行为$值){
      回声$价值。 ;
      $值= utf8_en code($值);
      回声$价值。 ;
    }

    $ R [] = $行;
  }
 

显示的值: 5482 5482 Abordâ普劳夫Abord¢?普劳夫

该阵列然后连接codeD使用 json_en code

  $行= db_fetch_all($结果);
回声json_en code($行);
 

问题

Web浏览器收到以下值:

  {ID:5482,姓名:空}
 

相反的:

  {ID:5482,姓名:AbordÂ普罗菲}
 

(或EN codeD等价的。)

问题

该文档指出 json_en code()适用于UTF-8。我能看到的值是EN codeD从LATIN1为UTF-8。 C $ C(),但是,值变为

调用 json_en $后

我如何 json_en code()连接code中的UTF-8的值是否正确?

一种可能的解决方案是使用<一href="http://www.zfforums.com/zend-framework-general-discussions-1/general-q-zend-framework-2/json-encoding-breaks-strings-containing-special-characters-210.html">Zend框架,但我宁愿没有,如果它是可以避免的。

解决方案

  //创建一个空数组的EN codeD结果集
$行=阵列();

//遍历数据库的结果集,并把连接codeD值到$行
而($行= mysql_fetch_assoc($结果)){
  $行[] = array_map('utf8_en code',$行);
}

//输出$行
回声json_en code($行);
 

Quest

I am looking to fetch rows that have accented characters. The encoding for the column (NAME) is 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

The array is then encoded using json_encode:

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

Problem

The web browser receives the following value:

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

Instead of:

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

(Or the encoded equivalent.)

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?

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_en code()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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