Reputation: 559
I have been trying to solve this for more than a week.
I have a MySQL database utf8_general_ci.
When I print the result in JSON formate using php, the characters are not UTF8 encoded.
The values stored in the database are in arabic language
Here is the code I'm using
db.php
<?php
$DBhost = "xx.xx.xx.x";
$DBusername = "username";
$DBpassword = "password";
$db_name = "bdname";
$connect = mysql_connect("$DBhost", "$DBusername", "$DBpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>
and code to print the results are
Show.php
<?php
include('db.php');
$tbl_name = "table_name";
mysql_set_charset('utf8');
$sth = mysql_query("SELECT * FROM $tbl_name");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = array_map('utf8_encode', $r);
}
print json_encode($rows);
?>
Example of the output:
[{"id":"4","news_id":"1","caption":"\u00c3\u0083\u00c3\u008e\u00c3\u0088\u00c3\u0087\u00c3\u0091 \u00c3\u0087\u00c3\u00a1\u00c3\u0088\u00c3\u0098\u00c3\u00a6\u00c3\u00a1\u00c3\u0089 \u00c3\u0087\u00c3\u00a1\u00c3\u00a3\u00c3\u008f\u00c3\u0091\u00c3\u0093\u00c3\u00ad\u00c3\u0089 \u00c3\u0087\u00c3\u00a1\u00c3\u008e\u00c3\u0087\u00c3\u00a3\u00c3\u0093\u00c3\u0089 \u00c3\u00a1\u00c3\u009f\u00c3\u0091\u00c3\u0089 \u00c3\u0087\u00c3\u00a1\u00c3\u009e\u00c3\u008f\u00c3\u00a3"
What I understood from my search that the /u00 is a latin1 and the UTF8 should start with /u0 not two 0.
Tried different methods for converting latin1 to UTF8 like iconv and decode_json , changing the mysql_set_charset to latin1 and even removing it, added html header using UTF8,latin1 and windows-1526 charset also the same results and sometime i get null result for the caption output.
I'm out of options here and really don't know what to do
any idea ?
Upvotes: 1
Views: 4211
Reputation: 191
Include the next header in your .php file
<?php
header('Content-type: application/json; charset=UTF-8');
...
and add 'JSON_UNESCAPED_UNICODE' in your json_encode
echo json_encode($response, JSON_UNESCAPED_UNICODE);
Be sure to remove the utf8_encode() unnecessary.
Upvotes: 3
Reputation: 6024
When you use mysql_set_charset('utf8');
you get utf-8
encoded data from MySQL databse. Don't usearray_map('utf8_encode', $r)
on this data - this is your mistake. Correct one is:
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
Upvotes: 0