【问题标题】:PHP UTF-8 Encoding is messing upPHP UTF-8 编码搞砸了
【发布时间】:2013-12-30 04:34:38
【问题描述】:

我正在将我的数据库中的一些多语言数据输出到 JSON 对象中,但输出没有显示外来字符,即使我将标题字符集设置为 utf8,它也只显示问号:

header('Content-Type: application/json; charset=utf-8');

当我查看 phpMyAdmin 中的数据时,它正确显示了字符。是不是我做错了什么?

这是格式化 JSON 输出的 PHP 代码:

$numRows = new stdClass();

$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($stmt = $mysqli->prepare($query)) {
    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();
    $numRows->cc = $stmt->num_rows;

    /* close statement */
    $stmt->close();
}
$mysqli->close();

$count = 0;
$dataCountryCodes = '{';
    $mysqli = dbiConnect();
    $query = "SELECT * FROM country_codes";
    if ($result = $mysqli->query($query)) {
        while($row = $result->fetch_assoc()){
            $count++;
            $rowData = new stdClass();
            $rowData->code = $row['code'];
            $rowData->name = $row['name'];
            $dataCountryCodes = $dataCountryCodes.'"'.$rowData->code.'": {"Code":"'.$rowData->code.'","Country":"'.$rowData->name.'"}';

            if ($count != $numRows->cc) {
                $dataCountryCodes = $dataCountryCodes.',';
            }
        }
    }
    $mysqli->close();
$dataCountryCodes = $dataCountryCodes.'}';
if ($returnCountryCodes == 1) {
    return $dataCountryCodes;
} else {

    header('Content-Type: application/json; charset=utf-8');
    echo ($dataCountryCodes);
}

这就是我得到的:

{"AE": {"Code":"AE","Country":"United Arab Emirates (???????? ???????? ????????)"}}

这是我在手动编码时得到的,在我将 JSON 转换为 HTML 后会很好地呈现:

{"AE": {"Code":"AE","Country":"United Arab Emirates (الإمارات العربيّة المتّحدة)"}}

【问题讨论】:

  • 您确定从数据库中出来的数据是正确的,还是一开始就正确地放入了数据库中?您的数据库表/字段可能设置为 utf-8,但您的 ENTIRE 渲染管道也必须设置为 utf-8,包括 phpdb 连接。 phpmyadmin 可能正确显示它,因为它具有正确配置的连接,而您的代码不是
  • @MarcB 我添加了更多细节,当我在数据库管理工具中查看时数据库中的数据很好......
  • dbiConnect() 里面有什么?我猜你的数据库连接字符集定义不正确。

标签: php mysql json utf-8 multilingual


【解决方案1】:

您没有显示 dbiConnect 功能。检查它并在连接到 MySQL 后尝试使用SET NAMES 'UTF8'

$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
    die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}

/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $con->error);
}

正如manual 所说:

SET NAMES 表示客户端将使用什么字符集发送 SQL 对服务器的语句...它还指定服务器应该使用的字符集 用于将结果发送回客户端。

【讨论】:

    【解决方案2】:

    试试这个:

    $mysqli = dbiConnect();
    $mysqli->query("set names utf8")
    

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 2013-10-31
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2012-06-08
      • 1970-01-01
      相关资源
      最近更新 更多