【问题标题】:Github API JSON Call returning nothing in PHPGithub API JSON 调用在 PHP 中不返回任何内容
【发布时间】:2017-03-26 00:01:28
【问题描述】:

我正在尝试使用 Github Api 从这个 Api 调用中获取数据。但是,每当我尝试从中获取数据时,都会出现以下错误。我似乎无法弄清楚为什么这不起作用。

我通过 PhpStorm 在本地主机上运行它。

代码:

$url = urlencode("https://api.github.com/users/devinmatte/repos");
$json = file_get_contents($url);
$obj = json_decode($json);
echo $obj;

错误:

[Sat Mar 25 20:02:14 2017] PHP Warning:  file_get_contents(https%3A%2F%2Fapi.github.com%2Fusers%2Fdevinmatte%2Frepos): failed to open stream: No such file or directory in /home/devin-matte/Documents/Git-Challenge/index.php on line 13

【问题讨论】:

  • 出于好奇,什么是“git挑战”?
  • Git-Challenge 是我正在进行的项目的名称。我正在尝试为学生的 git 存储库做出 Game-ify 贡献。

标签: php json github github-api


【解决方案1】:

有几个错误:

  • 不需要urlencode网址
  • 您需要创建上下文
  • 您需要print_rvar_export 等而不是echo 来打印数组的内容。

这应该可以完成工作:

$url = "http://api.github.com/users/devinmatte/repos";
$opts = [
    'http' => [
        'method' => 'GET',
        'header' => [
                'User-Agent: PHP'
        ]
    ]
];

$json = file_get_contents($url, false, stream_context_create($opts));
$obj = json_decode($json);
var_dump($obj);

【讨论】:

    【解决方案2】:

    您正在对整个 URI 进行 url 编码,file_get_contents 期望 一个有效的 http URI:

    $json = file_get_contents("https://api.github.com/users/devinmatte/repos");
    $obj = json_decode($json);
    var_dump($obj);
    

    【讨论】:

    • 运行该代码会使$obj = NULL 尽管api.github.com/users/devinmatte/repos 绝对不是空JSON 对象
    • 我知道这是我的日志:[Sat Mar 25 20:30:15 2017] PHP Warning: file_get_contents(https://api.github.com/users/devinmatte/repos): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /home/devin-matte/Documents/Git-Challenge/index.php on line 12
    • 检查this issue,它可能是allow_url_fopen 未在php.ini 中设置为Onuser_agent 未在php.ini 中设置
    猜你喜欢
    • 2014-02-18
    • 2015-03-14
    • 2014-03-24
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多