0

I am android developer. And I get my data from MySQL database via PHP code:

<?php

    $con = mysqli_connect("..........", "...........", "........", "......");

  $query = mysqli_query($con,
           "SELECT * FROM news WHERE status = 'actual' ORDER BY id DESC");
$someArray = [];
$someArray;

  // Loop through query and push results into $someArray;
  while ($row = mysqli_fetch_assoc($query)) {
    array_push($someArray, [
        'id' => $row['id'],
'title' => $row['title'],
'text' => $row['text'],
'date' =>$row['date']
 ]);
  }

  $someJSON = json_encode($someArray);

echo  $someJSON;
?>

and it works for data with english letters , but when i tried to add in my database russian letters or letters like "ə ç ı ş ü ö ğ and etc." - it is not working. I have researched and found that i must add this:

<meta charset="utf-8"/>

at the top of PHP code, but it still not working, then i was researching more and found that I should correct $someJSON , and make it look like that:

  $someJSON = json_encode($someArray, JSON_UNESCAPED_UNICODE);

and it still not working

the part with russian letters looks like that :

{"id":"4","title":"????????","text":"????????? ??????? ?????, ? ??? ????????? ?? ?????????","date":"21.08.18"}

in my database for "title" it is :utf8mb4_unicode_520_ci for "text" it is : utf8_unicode_520_ci
(I don't know difference just make it different in case if one of them works)

How to make it show russian letters(and other non-english) with JSON Object?

  • Did you try `mb_convert_encoding($str, 'UTF-8', 'auto');` [Check this Link](http://php.net/manual/en/function.mb-convert-encoding.php) – Viraj Patel Aug 21 '18 at 13:12
  • 1
    Check the charset of mysqli client, `printf("Client character set: %s\n", $mysqli->character_set_name());` And also the [charset and collation of the db](https://dev.mysql.com/doc/refman/8.0/en/charset.html) – rckrd Aug 21 '18 at 13:12
  • @VirajPatel , I need JSON encode... but i tried `$someJSON = json_encode(mb_convert_encoding($someArray,'UTF-8', 'auto'), JSON_UNESCAPED_UNICODE);` it is not working ... output is "null" – Java Rzayev Aug 21 '18 at 13:49
  • @rckrd , where should I add this line? I have added it before echo, and it has showd me Error – Java Rzayev Aug 21 '18 at 13:52
  • Do not use any encode/decode, two wrongs does not make a right; it just makes a bigger mess. – Rick James Aug 23 '18 at 18:56

1 Answers1

0
$someJSON = json_encode($someArray, JSON_UNESCAPED_UNICODE);

is fine. The problem is elsewhere. See "question mark" in here

The most likely cause/fix:

The column in the database table is not CHARACTER SET utf8 (or utf8mb4). Fix this. (Verify with SHOW CREATE TABLE.)

Note: the JSON really has question marks; the data cannot be recovered from it. You must go back and rebuild the JSON.

Rick James
  • 135,179
  • 13
  • 127
  • 222