Use file_get_contents($url); to return json. It cannot be parsed using json_decode. What should I do? I have also used the curl method, but it does not work
This problem has been solved by myself. The data returned by the third party is ascll, so it needs to be converted into utf-8 format. It has nothing to do with json_decode
You need to verify whether the format is correct, do not upload the code on BB:
<?php
function treatJsonString($string)
{
$jsonData = json_decode($string, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $jsonData;
break;
case JSON_ERROR_DEPTH:
print '[Error] - Maximum stack depth exceeded' . PHP_EOL;
break;
case JSON_ERROR_STATE_MISMATCH:
print '[Error] - Underflow or the modes mismatch' . PHP_EOL;
break;
case JSON_ERROR_CTRL_CHAR:
print '[Error] - Unexpected control character found' . PHP_EOL;
break;
case JSON_ERROR_SYNTAX:
print '[Error] - Syntax error, malformed JSON' . PHP_EOL;
break;
case JSON_ERROR_UTF8:
print '[Error] - Malformed UTF-8 characters, possibly incorrectly encoded' . PHP_EOL;
break;
default:
print '[Error] - Unknown error' . PHP_EOL;
break;
}
return null;
}
$jsonString = '{"x":123,"s":[{"a":"1"}]';
var_dump(treatJsonString($jsonString));
First check whether your json is in normal json format
Then check whether your php file is utf-8 without BOM
I have encountered similar problems before, and it will be fine after removing the BOM~
json_decode($json, true)
With true, it means it will be parsed into an array of php
First, make sure your Json is escaped in other ways. If not, you can use the Json formatting verification tool to check if there is a problem.
Online Json format verification tool
http://www.bejson.com/