Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

David Jones picture David Jones · May 11, 2013 · Viewed 194.3k times · Source

I have a PHP script that deals with a wide variety of languages. Unfortunately, whenever I try to use json_encode, any Unicode output is converted to hexadecimal entities. Is this the expected behavior? Is there any way to convert the output to UTF-8 characters?

Here's an example of what I'm seeing:

INPUT

echo $text;

OUTPUT

База данни грешка.

INPUT

json_encode($text);

OUTPUT

"\u0411\u0430\u0437\u0430 \u0434\u0430\u043d\u043d\u0438 \u0433\u0440\u0435\u0448\u043a\u0430."

Answer

John Severinson picture John Severinson · May 11, 2013

Since PHP/5.4.0, there is an option called JSON_UNESCAPED_UNICODE. Check it out:

https://php.net/function.json-encode

Therefore you should try:

json_encode( $text, JSON_UNESCAPED_UNICODE );