UTF-8字符编码与json_encode()较量
:
UTF-8贯穿始终 (15个答案)
5年前关闭。
我正在寻找具有重音符号的行。列(NAME
)的编码为latin1_swedish_ci
。
以下查询Abord â Plouffe
使用phpMyAdmin 返回:
SELECT C.NAME FROM CITY CWHERE C.REGION_ID=10 AND C.NAME_LOWERCASE LIKE '%abor%'
ORDER BY C.NAME LIMIT 30
以下显示期望值(称为函数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
以下代码对数组进行编码:
$rows = db_fetch_all( $result );echo json_encode( $rows );
Web浏览器收到以下值:
{"ID":"5482","NAME":null}
代替:
{"ID":"5482","NAME":"Abord â Plouffe"}
(或等效的编码形式。)
文档指出json_encode()
可以在UTF-8上使用。我可以看到将值从LATIN1编码为UTF-8。json_encode()
但是,在调用后,该值变为null
。
如何json_encode()
正确编码UTF-8值?
一种可能的解决方案是使用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);
以上是 UTF-8字符编码与json_encode()较量 的全部内容, 来源链接: utcz.com/qa/398907.html