0

I am having trouble with the output of json_encode. I need to output Russian characters.

In my database table only Russian characters. In the output I am getting only "????????" question marks replaced Russian characters. I read many similar questions but none of them offered a real solution. I tried the following but none of them helped.

Below is my php code.

  1. added ``header ('Content-type: application/json; charset=utf-8');`
  2. used json_encode($albums, JSON_UNESCAPED_UNICODE);
  3. tried mb_convert_encoding($str, 'UTF-8', 'auto'); json_encode($albums, JSON_UNESCAPED_UNICODE);
<?php
    $host ="localhost";
    $user ="misollar_user";
    $pass="12345";
    $db="misollar_db";
    header ('Content-type: application/json; charset=utf-8');
    $con = mysqli_connect($host,$user,$pass,$db);
    $query = "select * from albums;";
    $result = mysqli_query($con, $query);
    $albums = array();
    while ($row = mysqli_fetch_array($result)){
        array_push($albums,array('id'=>$row[0], 'name'=>$row[1], 'songs_count'=>$row[2]));
    }
    mysqli_close($con);
    echo json_encode($albums, JSON_UNESCAPED_UNICODE);
?>
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
Nodirbek
  • 3
  • 4

1 Answers1

0

You need to set UTF8 before retrieving results from mysql.

Just before you retrieve results from albums table, fire below query:

mysqli_query($con, 'SET names UTF8');

After this you can fetch your album results:

$query = "select * from albums;";
$result = mysqli_query($con, $query);
Samir Selia
  • 7,007
  • 2
  • 11
  • 30
  • Thank You Samir, this really helped me. I really appretiate your help. I have been searching on google, and digging stackoverflow for the solution for many hours. Thank you once again. – Nodirbek Nov 25 '16 at 09:45
  • Happy coding :) – Samir Selia Nov 25 '16 at 09:49
  • Dear Samir, I managed to get Russian characters on the browser, link (http://misollar.uz/albums.php) but My android app is not reading the same characters when I parse with JSON. The out put is quite different "D" like characters, any idea how this can be fixed? – Nodirbek Nov 25 '16 at 10:24
  • 1
    Prefer using `mysqli_set_charset` to define charset to an explicit SET NAMES. MySQL documentation states, about the C function mysql_real_escape_string, behind mysqli_real_escape_string: "If you must change the character set of the connection, use the mysql_set_character_set() function rather than executing a SET NAMES (or SET CHARACTER SET) statement. mysql_set_character_set() works like SET NAMES but also affects the character set used by mysql_real_escape_string(), **which SET NAMES does not**." (mysql_set_character_set is the C function behind mysqli_set_character_set) – julp Nov 25 '16 at 10:45