Search code examples
phpjsonunicodeutf-8cyrillic

json_encode error for russian characters


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);
?>

Solution

  • 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);