【问题标题】:json_encode runtime warning "Invalid UTF-8 sequence"json_encode 运行时警告“无效的 UTF-8 序列”
【发布时间】:2012-07-10 12:15:48
【问题描述】:

我从数据库中检索一个 mysqli-resultset,来自一个 utf-8 编码的表,然后插入到一个数组中:

$json = array();

$query = "select artikel_titel from tblArtikel";
if($result = mysqli_query($link, $query))
{
    while($line = mysqli_fetch_array($result, MYSQLI_NUM)) {
    array_push($json, $line);
}
echo json_encode($json);

数组已正确构建,you can see it here 在页面底部,您可以看到 json_encode 创建的错误。我该如何解决这个问题?

Warning: json_encode(): Invalid UTF-8 sequence in argument in /customers/6/0/6/onezeromany.com/httpd.www/php/getArticles.php on line 13 Warning: json_encode(): Invalid UTF-8 sequence in argument in /customers/6/0/6/onezeromany.com/httpd.www/php/getArticles.php on line 13 Warning: json_encode(): Invalid UTF-8 sequence in argument in /customers/6/0/6/onezeromany.com/httpd.www/php/getArticles.php on line 13

【问题讨论】:

    标签: php json


    【解决方案1】:

    确实在您的数据中有无效的 UTF-8 序列;显然您的数据库结果在 ISO-8859-1 中。根据the docsjson_encode适用于 UTF-8 数据。您必须确保您的数据采用 UTF-8 格式,并且您的数据库连接也使用 UTF-8 格式;或者,您可以使用 iconv() 将结果转换为 UTF-8,然后再将它们提供给 json_encode

    【讨论】:

    • 谢谢。你能告诉我你是怎么发现它们不是 UTF-8 的吗?
    • 您的转储在多个字符串中显示了 Unicode replacement character,在我将浏览器的编码强制为 ISO-8859-1 后正确显示。
    【解决方案2】:

    我遇到了同样的问题,在 mysqli connect 语句解决了问题后使用了mysqli_set_charset

    $con = mysqli_connect('localhost', 'my_user', 'my_password', 'test');
    mysqli_set_charset($con, 'utf8');
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      相关资源
      最近更新 更多