Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode runtime warning "Invalid UTF-8 sequence"

Tags:

json

php

I retrieve a mysqli-resultset from the database, comes from a utf-8 encoded table and then is inserted into an array:

$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 here At the bottom of the page you can see the error created by the json_encode. How can I fix this?

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
like image 920
Veltar Avatar asked Dec 20 '22 19:12

Veltar


2 Answers

You do have an invalid UTF-8 sequence in your data; apparently your database results are in ISO-8859-1. json_encode works only with 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.

like image 51
lanzz Avatar answered Dec 29 '22 21:12

lanzz


I had the same problem and using mysqli_set_charset after the mysqli connect statement solved the problem.

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

Hope it helps!

like image 38
pmrotule Avatar answered Dec 29 '22 21:12

pmrotule