【问题标题】:How to put in JSON Object non-english letters?如何放入 JSON Object 非英文字母?
【发布时间】:2018-08-21 12:56:41
【问题描述】:

我是安卓开发者。我通过 PHP 代码从 MySQL 数据库中获取数据:

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

它适用于带有英文字母的数据,但是当我尝试在我的数据库中添加俄语字母或诸如“ə ç ı ş ü ö ğ 等”之类的字母时。 - 它不工作。 我研究过,发现我必须添加这个:

<meta charset="utf-8"/>

在PHP代码的顶部,但它仍然无法正常工作,然后我研究了更多,发现我应该更正$someJSON,并使其看起来像这样:

  $someJSON = json_encode($someArray, JSON_UNESCAPED_UNICODE);

还是不行

带有俄文字母的部分是这样的:

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

在我的“标题”数据库中,它是:utf8mb4_unicode_520_ci 对于“文本”,它是:utf8_unicode_520_ci
(我不知道有什么区别,只是在其中一个有效的情况下有所不同)

如何使用 JSON 对象使其显示俄语字母(和其他非英语)?

【问题讨论】:

  • 你试过了吗mb_convert_encoding($str, 'UTF-8', 'auto');Check this Link
  • 检查mysqli客户端的字符集printf("Client character set: %s\n", $mysqli-&gt;character_set_name());还有charset and collation of the db
  • @VirajPatel,我需要 JSON 编码...但我试过 $someJSON = json_encode(mb_convert_encoding($someArray,'UTF-8', 'auto'), JSON_UNESCAPED_UNICODE); 它不起作用...输出为“null”
  • @rckrd ,我应该在哪里添加这一行?我在echo之前添加了它,它显示了错误
  • 不要使用任何encode/decode,二错不成对;它只会造成更大的混乱。

标签: php android mysql json utf-8


【解决方案1】:
$someJSON = json_encode($someArray, JSON_UNESCAPED_UNICODE);

没问题。问题在别处。见here中的“问号”

最可能的原因/修复:

数据库表中的列不是CHARACTER SET utf8(或utf8mb4)。解决这个问题。 (通过SHOW CREATE TABLE 验证。)

注意:JSON 确实有问号;无法从中恢复数据。您必须返回并重建 JSON。

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2021-12-18
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多