php - cUrl 正在返回 JSON 字符串,json_decode 没有将其解码为对象或数组

标签 php json github-api

我正在使用 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,如此处解释

curl_exec

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 字符串,这回答了这个问题

CURLOPT_RETURNTRANSFER

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/

相关文章:

php - file() 在读取时是否锁定文件?

javascript - 如何在 JavaScript 中重构 JSON?

java - 尝试在 Java 中将 List 从数据库转换为 json 时的 Stackoverflow

PHP MySQL - 在不存储 key 的情况下动态加密解密数据

php - 'session.gc-maxlifetime' 始终为默认值

php - 填充数组php的算法

powershell - 为 github 存储库中的环境创建审阅者

json - jq 日期和 unix 时间戳

github - 如何通过合作者搜索github repo

json - 使用curl通过Github API v3创建新的gist