How to Solve JSON_Error_Utf8 Error in PHP JSON_Decode

json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT

Before you JSON encode, use utf8_encode() around the string.

PHP array not converting to JSON using json_encode

If json_last_error gives you the JSON_ERROR_UTF8 error code (5), then you will have to encode your datas in UTF-8 :

Need to convert final array to utf-8.

<?php

$response = array_map('utf8_encode', $response);

json_encode returns JSON_ERROR_UTF8 when converting array to JSON

"If I try to connect to the database using charset=utf8 or charset=utf8mb4, it retrieves Cartão(bad codification), instead of Cartão (good codification)"

You are using latin1 as the display encoding, so that UTF-8 encoded, correct, text is displayed incorrectly.

Add charset=utf8 to the connection string and also set the response charset to UTF-8:

header('Content-Type: text/html;charset=utf-8');

How to fix a JSON_ERROR_UTF8

You can remove them:

 $string = preg_replace('/[^[:print:]]/', '', $string);

Which removes any non-printable characters (but it will remove some stuff), it's a lot harder to replace them, a lot of edge case stuff.

But as you are getting these from the DB you can try to set the charset on the DB connection:

mysqli_set_charset( $link ,'utf8' );
//Or if you are using the OOP mysqli
$conn->set_charset('utf8');
//Or PDO
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);

Which may fix the issue too. The best bet is to clean the data up when inserting it into the DB.

Why would json_encode return false in this case?

From PHP's manpage for json_last_error():

JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded (PHP 5.3.3)

You have to ensure that the data given to json_encode() is UTF8, you should try using iconv to convert your strings to a proper format.

JSON_ERROR_UTF8(5) error while json_decode

Handle json_decode error as follow using json_last_error.

if ($json === null && json_last_error() !== JSON_ERROR_NONE) {
echo "Incorrect json data.";
}

If you've unsupported UTF-8 characters in your encoded json then convert them before decoding.

$input = Storage::disk('local')->get('users.json');
$json = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($input));
$arr = json_decode($json, true);

If possible I suggest you to do the same while doing json_encode.



Related Topics



Leave a reply



Submit