我正在使用 github 的 api 在 PHP 下拉取最流行的“加星标”项目,它拉取 json 字符串 ok。唯一的问题是我的 json_decode 仍然只是转储 JSON 字符串而不是对象。下面是我正在运行的函数。
private function fillTable(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.github.com/search/repositories?q=+language:php&sort=stars&order=desc',
CURLOPT_USERAGENT => 'trickell'
));
$res = curl_exec($curl);
var_dump(json_decode($res));
}
我不确定为什么它不将 json 字符串解码为对象。如果你运行它,你应该能够准确地看到是什么在拉动。
最佳答案
因为您没有要解码的 json,那是因为您没有告诉 cURL 将值返回给您,所以您正在尝试解码一个空字符串。
$res = curl_exec($curl);
除非您要求RETURNTRANSFER
,否则$res
只会是TRUE/FALSE,如此处解释
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
因此您必须向 cURL 调用添加另一个选项。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
你可能会问,如果没有返回,为什么你会看到 JSON 字符串,这回答了这个问题
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
(强调我的)
关于php - cUrl 正在返回 JSON 字符串,json_decode 没有将其解码为对象或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665065/