任务
我正在寻找具有重音字符的行。列 (NAME
) 的编码是 latin1_swedish_ci
。
守则
以下查询使用 phpMyAdmin 返回 Abord â Plouffe
:
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)
):
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 );
问题
网络浏览器接收到以下值:
{"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);
https://stackoverflow.com/questions/2790027/