How to Preserve Special Characters in JSON using json_encode?

Mary-Kate Olsen
Release: 2024-10-18 17:12:29
Original
140 people have browsed it

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>
Copy after login
  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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!