json_encode运行时警告”;无效的UTF-8序列“;


json_encode runtime warning "Invalid UTF-8 sequence"

我从数据库中检索一个mysqli结果集,它来自一个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);

数组构建正确,您可以在此处看到在页面底部,您可以看到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

您的数据中存在无效的UTF-8序列;显然,您的数据库结果在ISO-8859-1中。据文档介绍,json_encode只能使用UTF-8数据。您必须确保您的数据是UTF-8格式的,并且您的数据库连接也使用UTF-8;或者,在将结果提供给json_encode之前,可以使用iconv()将结果转换为UTF-8。

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

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

希望它能有所帮助!