Fix JSON Decode Error Caused by Special Characters in PHP

1. Error description

For example, the following valid JSON string:

json
1
{"code":200,"name":"This is a Chinese character"}

Use the following code to parse:

PHP
1
$data = json_decode(mb_convert_encoding($txt, 'UTF-8'), true);

Error JSON invalid.

2. Solution

The problem maybe is that there are invisible characters, you can try to remove:

PHP
1
$data = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', mb_convert_encoding($txt, 'UTF-8')), true);

According to the test, the problem can be solved, if it still can't be solved, you can try to check whether the slash/backslash is grammatical.

Fix JSON Decode Error Caused by Special Characters in PHP

https://blog.tsinbei.com/en/archives/751/

Author
Hsukqi Lee
Posted on

2023-06-22

Edited on

2023-06-22

Licensed under

CC BY-NC-ND 4.0

Comments

Name
Mail
Site
None yet