1

I'm trying to get the data from this Api call with the Github Api. However whenever I try and get the data from it I get the below error. I cannot seem to figure out why this isn't working.

I'm running it on a localhost through PhpStorm.

Code:

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

Error:

[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
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Devin Matté
  • 183
  • 3
  • 12

2 Answers2

4

There are few errors:

  • no need to urlencode the url
  • you need to create context
  • you need to print_r, var_export etc instead of echo to print content of an array.

This should do the job:

$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);
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
2

You are url encoding the whole URI, file_get_contents expect a valid http URI :

$json = file_get_contents("https://api.github.com/users/devinmatte/repos");
$obj = json_decode($json);
var_dump($obj);
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • Running that code makes `$obj = NULL` despite https://api.github.com/users/devinmatte/repos definitely not being a null JSON object – Devin Matté Mar 26 '17 at 00:25
  • I get this is my Log: `[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` – Devin Matté Mar 26 '17 at 00:31
  • check [this issue](http://stackoverflow.com/questions/4545790/file-get-contents-returns-403-forbidden), it could be `allow_url_fopen` not set to `On` in `php.ini` or `user_agent` not set in `php.ini` – Bertrand Martel Mar 26 '17 at 00:32