Home  >  Article  >  Backend Development  >  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?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 17:10:03159browse

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:

<code class="php">$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);</code>

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:

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

With UTF-8 Encoding:

<code class="php">$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"}</code>

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

The above is the detailed content of How to Correctly Encode Special Characters in JSON with PHP\'s json_encode() Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn