php json_encode 运行时警告“无效的 UTF-8 序列”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11413116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
json_encode runtime warning "Invalid UTF-8 sequence"
提问by Veltar
I retrieve a mysqli-resultset from the database, comes from a utf-8 encoded table and then is inserted into an array:
我从数据库中检索一个 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);
The array is correctly built, you can see it hereAt the bottom of the page you can see the error created by the json_encode. How can I fix this?
数组构建正确,你可以在这里看到它 在页面底部你可以看到 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
回答by lanzz
You dohave an invalid UTF-8 sequence in your data; apparently your database results are in ISO-8859-1. json_encodeworks onlywith UTF-8 data, according to the docs. You'll have to ensure that your data is in UTF-8 and your database connection uses UTF-8 as well; alternatively, you can use iconv()to convert your results to UTF-8 before feeding them to json_encode.
您的数据中确实存在无效的 UTF-8 序列;显然您的数据库结果在 ISO-8859-1 中。json_encode工作仅使用UTF-8的数据,根据该文档。您必须确保您的数据采用 UTF-8 格式,并且您的数据库连接也使用 UTF-8;或者,您可以使用iconv()将结果转换为 UTF-8,然后再将它们提供给json_encode.
回答by pmrotule
I had the same problem and using mysqli_set_charsetafter the mysqli connect statement solved the problem.
我遇到了同样的问题,并且在 mysqli connect 语句解决了问题后使用了mysqli_set_charset。
$con = mysqli_connect('localhost', 'my_user', 'my_password', 'test');
mysqli_set_charset($con, 'utf8');
Hope it helps!
希望能帮助到你!

