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!