Home >Backend Development >PHP Tutorial >How to Preserve Special Characters in JSON using json_encode?

How to Preserve Special Characters in JSON using json_encode?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 17:12:29248browse

How to Preserve Special Characters in JSON using json_encode?

JSON Encoding Special Characters with json_encode

When working with arrays containing special characters, you may encounter a situation where these characters are converted to empty strings during JSON encoding using the json_encode function. This issue has been reported with characters such as copyright and trademark symbols.

To address this problem, ensure that the string data is UTF-8 encoded, as specified in the json_encode documentation. Here's a solution to resolve the issue:

  1. Before encoding the array, use the array_map function to apply utf8_encode to each element.
<code class="php">$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);</code>
  1. This will encode the special characters correctly, resulting in a JSON string that includes the symbols as expected.
<code class="json">// {"funds":"ComStage STOXX®Europe 600 Techn NR ETF"}</code>

It's crucial to note that for consistency, utf8_encode() should be used rather than htmlentities().

Refer to the following documentation for more information:

  • [json_encode()](https://www.php.net/manual/en/function.json-encode.php)
  • [utf8_encode()](https://www.php.net/manual/en/function.utf8-encode.php)
  • [array_map()](https://www.php.net/manual/en/function.array-map.php)

The above is the detailed content of How to Preserve Special Characters in JSON using json_encode?. 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