Ad

Handle When Api Doesn't Respond

- 1 answer

I am trying to get euro, dollar and turkish liras currencies and comparing them. But sometimes api (i am using a random currency website json values) can't respond. Cannot get any value and page loading 30 sec, after execute time was done, error appears. What i am trying to do is: if it couldn't get any value in 1 second(or less) from api, return null. How can i do that. If anybody can help, i would glad. This is my php codes. I was tried to use if else in this, but can't worked.

ps: I have a ajax codes for that, its refreshing when the value are change. This is working most times. But 2-3 times in a day, it throws error.

$json_eur = file_get_contents('https://doviz.com/api/v1/currencies/EUR/latest');
$val_eur = json_decode($json_eur, true);

echo $val_eur['selling'];

EDIT

This is the solve. Added some codes to JRoss answer.

$ctx_dollar = stream_context_create(array(
    'http' => array(
        'timeout' => 1
    )
)
);
$usd_url = 'https://doviz.com/api/v1/currencies/USD/latest';

if (@file_get_contents($usd_url)):
    $json_usd = file_get_contents($usd_url, 0, $ctx_dollar);
    $val_usd = json_decode($json_usd, true);
    if (is_numeric($val_usd['selling'])) {
        echo $val_usd['selling'];
    }
    else {
        echo "loading...";
    }
endif;
Ad

Answer

$ctx = stream_context_create(array( 
    'http' => array( 
        'timeout' => 1 
        ) 
    ) 
); 
file_get_contents("https://doviz.com/api/v1/currencies/EUR/latest", 0, $ctx); 

http://php.net/file_get_contents

and on top of that I would catch exceptions. try {} catch (Exception $e) {}

Ad
source: stackoverflow.com
Ad