May 17

json_encode(): Invalid UTF-8 sequence in argument and SLIM

Yesterday i stumbled on this error : json_encode(): Invalid UTF-8 sequence in argument . Searching on the net doesn’t resolve the issue but as usual gives me some other point of view to find the solution.


I’m using Slim Framework and a Mysqli connection to retrieve data from a MySQL Database, then i want to output the result of the query encoded in JSON format.


json_encode() function takes only UTF8 as a good string to format in JSON, sono the problem seems to be a character encoding stuff. So we enforce mysqli query to use UTF8 ( the collation of the database is yet UTF8 ) . Take a look at the code:

$connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

$stmt = mysqli_stmt_init($conne);
$stmt->prepare(“SELECT * “
. “FROM your_table”
. “where your_filter “
. “order by your_order”
if ($stmt->execute()) {
$result = $stmt->get_result();
return $result;
} else {
return NULL;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>