Skip to content
PHP Logo

What are the best practices for ensuring JSON data is correctly encoded in PHP scripts?

To ensure JSON data is correctly encoded in PHP scripts, it is important to properly handle any special characters that may be present in the data. One way to do this is by using the `json_encode()` function with the `JSON_UNESCAPED_UNICODE` flag, which will ensure that Unicode characters are not escaped. Additionally, it is recommended to set the content type header to `application/json` before outputting the JSON data.

php
$data = ['name' => 'John Doe', 'age' => 30, 'city' => 'New York'];
$json_data = json_encode($data, JSON_UNESCAPED_UNICODE);

header('Content-Type: application/json');
echo $json_data;