0

I'm getting JSON arrays with file_get_contents, but if the page doesn't exist I want to give an message: Player not found. But now I get this error:

Warning: file_get_contents(urlwithan404errorhere) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in -------

I don't get this error when the api gives me an correct JSON array.

This is the code is use:

$gegevens = file_get_contents('');      
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];
Ryan B
  • 3,364
  • 21
  • 35
Chiel
  • 83
  • 10
  • If you are planning on working a lot with services, i suggest you take a look at guzzle, https://github.com/guzzle/guzzle, instead of doing this kind of stuf with file_get_contents. You will get cleaner and better code. – Michal Jul 07 '14 at 13:09
  • I just use it once, so no thanks :D – Chiel Jul 07 '14 at 13:14
  • This topic is already awnsered http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php: – YANTHO Jul 07 '14 at 13:15

2 Answers2

1

Your code could become like this:

$gegevens = @file_get_contents('');      

if ($gegevens !== FALSE) {
    $array_2 = json_decode($gegevens, TRUE);
    $summonerid = $array_2[$naam]["id"];
} else {
    $summonerid = 0;
}

Explanations:
* the @ in front of file_get_contents is to stop showing php error in case the request failed.
* if the $summonerid equals to 0, then you have no player found

machineaddict
  • 3,216
  • 8
  • 37
  • 61
1

Try something like this:

if (($gegevens = @file_get_contents('')) === false) {
    printf("<h1>Player not found!</h1>\n");
    return;
}

// ... continue here ...

The @ will suppress any error message if file_get_contents()fails. It will return falsein this case (use === for comparison to avoid confusion with empty files), which you can use for failure detection.

fbitterlich
  • 882
  • 7
  • 24