JSON_Encode Produce JSON_Error_Utf8 from Mssql-Select

json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT

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

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.

Php json_encode($array) return nothing while $array contain HTML values

Finally figure out issue by using utf8_encode();

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


Related Topics



Leave a reply



Submit