JSON Response not in UTF8

Hello,
I’have made a API application with SLIM 3 which returns JSON not in UTF8.
The data come from a db mySql (the encoding of the base is utf8_general_ci) and the charset of the driver is set to UTF8. Here is my spot container :

$container["spot"] = function ($container) {

    $config = new Config();
    $mysql = $config->addConnection("mysql", [
        "dbname" => getenv("DB_NAME"),
        "user" => getenv("DB_USER"),
        "password" => getenv("DB_PASSWORD"),
        "host" => getenv("DB_HOST"),
        "driver" => "pdo_mysql",
        "charset" => "utf8"
    ]);

At the end of the route :

return $response->withStatus(200)
->withHeader(“Content-Type”, “application/json;charset=utf-8”)
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));

But when i call the API with Postman, the JSON contains anormal characteres like Croiz\u00e9 instead of Croizé.

Have you got an idea please
Thank you.
Eric

Hello Eric,

Do you see “\u00e9” in the “pretty” JSON view in Postman, or just in the raw view? I would expect Postman to show “Croizé” in the pretty JSON view (how it should be displayed) and “Croiz\u00e9” in the raw view (how it was sent).

“Croiz\u00e9” and “Croizé” are equal JSON string notations for the string “Croizé”. Like   and   both show the same non-breaking space character in HTML.

In JSON unicode characters can be escaped using the \uxxxx notation, where xxxx is a hexadecimal number of a unicode character. The character with number 00E9 is é:

image

By default the json_encode function in PHP seems to escape non ASCII-characters in JSON using the \uxxxx notation.

Normally, you don’t have to worry about how PHP encodes these characters as long as you feed an UTF-8 encoded string to json_encode. If you want, you can add an additional flag to force PHP to disable escaping of the unicode characters:

return $response
    ->withStatus(200)
    ->withHeader(“Content-Type”, “application/json;charset=utf-8”)
    ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT |  JSON_UNESCAPED_UNICODE));  // add JSON_UNESCAPED_UNICODE flag