Can I retry file_get_contents() until it opens a stream?

file-get-contents, php

Solution

Since you didn't provide any code it's kind of hard to help you. But here is one way to do it.

$data = null;

while(!$data) {
    $json = file_get_contents($url);
    $data = json_decode($json); // Will return false if not valid JSON
}

// While loop won't stop until JSON was valid and $data contains an object
var_dump($data);

I suggest you throw some sort of increment variable in there to stop attempting after `X` scripts.

Problem

I am using PHP to get the contents of an API. The problem is, sometimes that API just sends back a 502 Bad Gateway error and the PHP code can’t parse the JSON and set the variables correctly. Is there some way I can keep trying until it works?

Original source