Skip to content
PHP Logo

How can the correct character encoding be maintained when working with JSON strings in PHP?

When working with JSON strings in PHP, the correct character encoding can be maintained by using the `json_encode()` function with the `JSON_UNESCAPED_UNICODE` flag. This flag ensures that Unicode characters are not escaped but are instead encoded as-is in the JSON output.

php
$data = ['name' => 'Jérémy', 'age' => 30];
$jsonString = json_encode($data, JSON_UNESCAPED_UNICODE);
echo $jsonString;