UTF-8 character encoding battles json_encode() [duplicate]
// Create an empty array for the encoded resultset$rows = array();// Loop over the db resultset and put encoded values into $rowswhile($row = mysql_fetch_assoc($result)) { $rows[] = array_map('utf8_encode', $row);}// Output $rowsecho json_encode($rows);
foreach( $row as $value ) { $value = utf8_encode( $value );
You're not actually writing your encoded value back into the $row
array there, you're only changing the local variable $value
. If you want to write back when you change the variable, you would need to treat it as a reference:
foreach( $row as &$value ) {
Personally I would try to avoid references where possible, and for this case instead use array_map
as posted by Kemo.
Or mysql_set_charset
to UTF-8 to get the return values in UTF-8 regardless of the actual table collations, as a first step towards migrating the app to UTF-8.
My solution is insert this line mysql_query('SET CHARACTER SET utf8');
, before the SELECT
.This method is good.