UTF-8字符编码战jason_encode()

Dav*_*vis 29 php mysql ajax json character-encoding

寻求

我想要获取具有重音字符的行.column(NAME)的编码是latin1_swedish_ci.

代码

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

SELECT C.NAME FROM CITY C
WHERE C.REGION_ID=10 AND C.NAME_LOWERCASE LIKE '%abor%'
ORDER BY C.NAME LIMIT 30
Run Code Online (Sandbox Code Playgroud)

以下显示预期值(调用函数db_fetch_all( $result )):

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

    $r[] = $row;
  }
Run Code Online (Sandbox Code Playgroud)

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

然后使用json_encode以下代码编码数组:

$rows = db_fetch_all( $result );
echo json_encode( $rows );
Run Code Online (Sandbox Code Playgroud)

问题

Web浏览器接收以下值:

{"ID":"5482","NAME":null}
Run Code Online (Sandbox Code Playgroud)

代替:

{"ID":"5482","NAME":"Abord â Plouffe"}
Run Code Online (Sandbox Code Playgroud)

(或编码的等价物.)

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

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

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

Kem*_*emo 38

// 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);
Run Code Online (Sandbox Code Playgroud)


bob*_*nce 11

foreach( $row as $value ) {
  $value = utf8_encode( $value );
Run Code Online (Sandbox Code Playgroud)

您实际上并没有将编码值写回到$row那里的数组中,而只是更改局部变量$value.如果要在更改变量时写回,则需要将其视为参考:

foreach( $row as &$value ) {
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会尽可能避免引用,而在这种情况下,请使用array_mapKemo发布的内容.

或者mysql_set_charset以UTF-8获取UTF-8的返回值,而不考虑实际的表归类,作为将应用程序迁移到UTF-8的第一步.


小智 5

我的解决方案是在插入此行mysql_query('SET CHARACTER SET utf8');之前SELECT.这种方法很好.