Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-18 17:10:03
Original
259 people have browsed it

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

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

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

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!

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