PHP json_encode() fails with error “Invalid UTF-8 sequence in argument”

Issue

PHP / MySQL web service fails to return JSON encoded data when it contains some non standard ASCII characters. Text in MySQL looks correctly and database has “utf8_unicode_ci” collation.
The issue occurs while running json_encode() function. The web service returns following error:

Type : Error Exception
Message: json_encode(): Invalid UTF-8 sequence in argument

 

 

Resolution

Even though the database collation was set to utf8, the PHP “mysli” connection was not using utf8. The issue was resolved by setting the connection encoding with set_charset(“utf8”);


$this->conn = new mysqli(HOST, USERNAME, PASSWORD, DB);
$this->conn->set_charset("utf8");

PHP 5.4
MySQL 5.5

 


Comments

Leave a Reply

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