The issue is I can't use any russian symbols in the response()->json()
method.
I've already tried the following code:
return response()->json(['users' => 'тест']);
and
return response()->json(['users' => mb_convert_encoding('тест', 'UTF-8')]);
and
return response()->json(
['users' => mb_convert_encoding('тест', 'UTF-8')])
->header('Content-Type', 'application/json; charset=utf-8');
I've checked the default encoding:
mb_detect_encoding('тест'); // returns 'UTF-8'
Also, all my files have been converter to UTF-8 without BOM. I've added the default character set to the .htaccess file(AddDefaultCharset utf-8
) as well.
But, I still get the wrong response like here:
{"users":"\u0442\u0435\u0441\u0442"}
UTF-8. 128 characters are encoded using 1 byte (the ASCII characters). 1920 characters are encoded using 2 bytes (Roman, Greek, Cyrillic, Coptic, Armenian, Hebrew, Arabic characters).
KOI8-R (RFC 1489) is an 8-bit character encoding, derived from the KOI-8 encoding by the programmer Andrei Chernov in 1993 and designed to cover Russian, which uses a Cyrillic alphabet. KOI8-R was based on Russian Morse code, which was created from a phonetic version of Latin Morse code.
The response that you are getting:
{"users":"\u0442\u0435\u0441\u0442"}
is valid JSON!
That being said, if you don't want to encode the UTF-8 characters, you can simply just do this:
$data = [ 'users' => 'тест' ];
$headers = [ 'Content-Type' => 'application/json; charset=utf-8' ];
return response()->json($data, 200, $headers, JSON_UNESCAPED_UNICODE);
The output would then be
{"users":"тест"}
Calling the response()
helper will create an instance of Illuminate\Routing\ResponseFactory
. ResponseFactory
's json
function has the following signature:
public function json($data = [], $status = 200, array $headers = [], $options = 0)
Calling json()
will create a new instance of Illuminate\Http\JsonResponse
, which will be the class responsible for running json_encode
for your data. Inside the setData
function in JsonResponse
, your array will be encoded with the $options
provided on the response()->json(...)
call:
json_encode($data, $this->jsonOptions);
As you can see on the documentation on php.net for the json_encode
function and the documentation on php.net for the json_encode
Predefined Constants, JSON_UNESCAPED_UNICODE
will encode multibyte Unicode characters literally (default is to escape as \uXXXX).
It is important to note that JSON_UNESCAPED_UNICODE
has only been supported since PHP 5.4.0, so make sure you are running 5.4.0 or newer to use this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With