"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Correctly Encode Special Characters in JSON with PHP\'s json_encode() Function?

How to Correctly Encode Special Characters in JSON with PHP\'s json_encode() Function?

Published on 2024-11-17
Browse:474

How to Correctly Encode Special Characters in JSON with PHP\'s json_encode() Function?

JSON Encoding and Special Characters

While encoding arrays using the json_encode() function, it may happen that elements containing special characters get converted to empty strings. This behavior is particularly noticeable with characters such as copyright or trademark symbols.

To resolve this issue, ensure that all string data is UTF-8 encoded before encoding it as JSON. This can be achieved by using array_map() in conjunction with the utf8_encode() function:

$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);

As noted in the PHP manual, json_encode() requires all string data to be UTF-8 encoded. By encoding the array elements to UTF-8 prior to JSON encoding, we ensure that special characters are correctly represented in the JSON output.

For clarity, let's compare the results of encoding an array with and without UTF-8 encoding:

Without UTF-8 Encoding:

$arr = ["funds" => "ComStage STOXX®Europe 600 Techn NR ETF"];
$json = json_encode($arr); // {"funds":null}

With UTF-8 Encoding:

$arr = array_map('utf8_encode', ["funds" => "ComStage STOXX®Europe 600 Techn NR ETF"]);
$json = json_encode($arr); // {"funds":"ComStage STOXX\u00c2\u00aeEurope 600 Techn NR ETF"}

By applying UTF-8 encoding, the special characters are correctly represented in the JSON output. Remember to use utf8_encode() consistently for proper encoding.

Release Statement This article is reprinted at: 1729242557 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3