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


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


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);

PHP 5.4
MySQL 5.5



Subscribe to receive occasional updates on new posts.
Your email will not be used for any other purpose and you can unsubscribe at any time.
Please wait