为什么我不能 json_decode 来自 API 的回复?

why i cant json_decode my response from API?

我试图从这个来源获取数据,这是我所在国家/地区的学校详细信息。但是当我收到回复时,我无法解码我的回复,它说 Null。我不知道为什么,但是当我尝试将我的响应结果复制并粘贴到硬编码时,它可以被解码。为什么?

我已经尝试了所有可能的方法来解决这个问题,但没有任何效果。

这是我的代码:

$client = new \GuzzleHttp\Client();

$res = $client->request('GET', 'http://jendela.data.kemdikbud.go.id/api/index.php/Csekolah/detailSekolahGET?mst_kode_wilayah=026700');

$response = $res->getBody()->getContents();

$result = json_decode($response); // this return NULL

//But when i going to return the $response, it show the response.

return $response;

我希望访问数据或者只是解码我的代码,这对我有很大帮助。

仅供参考,我正在使用 Guzzle 6 和 Laravel 5.7 来处理此问题。

我希望有人也能尝试访问它并帮助我。

或者如果你想测试它,你可以使用 Curl Ways :

$param = 'index.php/Csekolah/detailSekolahGET?mst_kode_wilayah=026700';
$url='http://jendela.data.kemdikbud.go.id/api/'.$param;

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec ($ch);
return $response;

json_decode 文档说:

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

可以使用json_last_error or json_last_error_msg函数来判断问题。

我无法得到完整的响应,它超时并终止了。

根据文档:

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit

来源:json_decode

一些调试技巧:

  1. 确保所有字符都在 utf8
  2. 范围内
  3. 指定深度值(高于默认值)
  4. 利用json_last_error见:json_last_error

如果调试提示 1 恰好是问题的原因,请查看是否可以限制 return 不包含违规字符。

删除行return $response;

并尝试以下代码:

$enc = mb_detect_encoding($response);

if($enc == 'UTF-8') {
  $response = preg_replace('/[^(\x20-\x7F)]*/','', $response);    
} 
echo "<pre>";
print_r(json_decode($response,true));