Home >Backend Development >PHP Tutorial >How Do I Handle Malformed UTF-8 Characters when Encoding JSON in PHP?

How Do I Handle Malformed UTF-8 Characters when Encoding JSON in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 08:03:30953browse

How Do I Handle Malformed UTF-8 Characters when Encoding JSON in PHP?

Malformed UTF-8 Characters in PHP JSON Encode

When using json_encode($data) in PHP, an error may occur if the data contains Russian characters due to malformed UTF-8 characters. The mb_detect_encoding() function may indicate that the encoding is UTF-8, but the presence of characters like "ра▒" can cause the encoding to be invalid.

To resolve this issue, consider removing any non-UTF-8 characters from the data using mb_convert_encoding():

<code class="php">$data['name'] = mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');</code>

This converts the string to UTF-8 encoding, ensuring that all characters are valid and the JSON encoding process should succeed.

The above is the detailed content of How Do I Handle Malformed UTF-8 Characters when Encoding JSON in PHP?. 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