Home > Backend Development > PHP7 > body text

Encountered a problem about php7 json_decode null!

藏色散人
Release: 2023-02-18 09:16:02
forward
2420 people have browsed it

Encountered a problem about php7 json_decode null!

Specific problem description:

1. Confirm that the file has no BOM header

2. Tried the following methods to remove illegal strings, but still Output NULL

        $some_string = htmlspecialchars_decode($some_string);
        $some_string = preg_replace("/\t/", " ", $some_string);
        $some_string = preg_replace("/\n/", ' ', $some_string);
        $some_string = str_replace("\n", ' ', $some_string);
        $some_string = str_replace ('\n','', $some_string);
Copy after login

3. json_last_error() outputs 4, Syntax error, malformed JSON

4. Directly output string, the browser can parse josn normally, as shown in the screenshot below

Encountered a problem about php7 json_decode null!

Solution:

Because your string is not a standard JSON string, each string type of a standard JSON string must be raised with "

test code

<?php 
$jsonStr1 = &#39;{status: {RetCode:0, msg: "success"}, data: {}}&#39;;
var_dump(json_decode($jsonStr1, true));
var_dump(json_last_error());
echo "--------分割线--------".PHP_EOL;
$jsonStr2 = &#39;{"status": {"RetCode":0, "msg": "success"}, "data": {}}&#39;;
var_dump(json_decode($jsonStr2, true));
Copy after login

result

NULL
int(4)
--------分割线--------
array(2) {
  ["status"]=>
  array(2) {
    ["RetCode"]=>
    int(0)
    ["msg"]=>
    string(7) "success"
  }
  ["data"]=>
  array(0) {
  }
}
Copy after login

============== Update======== ======

After debugging, it was found that it was caused by BOM. The following is the solution

$dataString = $merchant_arr[&#39;data&#39;];
$A = substr($dataString, 0, 1);
$B = substr($dataString, 1, 1);
$C = substr($dataString, 2, 1);
if ((ord($A) == 239) && (ord($B) == 187) && (ord($C) == 191)) {
    $dataString = substr($dataString, 3);
}
$dataArray = json_decode($dataString, true);
Copy after login

Recommended study: "PHP7 Tutorial"

The above is the detailed content of Encountered a problem about php7 json_decode null!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template