Q:

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

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?

A:

This is not an easy question because PHP is a synchronous language by default.
You could do this:
$a = false;
$i = 0;
while($a == false && $i < 10)
{
    $a = file_get_contents($path);
    $i++;
    usleep(10);
}

$result = json_decode($a);

Adding usleep(10) allows your server not to get on his knees each time the API will be unavailable. And your function will give up after 10 attempts, which prevents it to freeze completely in case of long unavailability.

A:

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.

