代码之家  ›  专栏  ›  技术社区  ›  Ali Özen

api不响应时处理

  •  0
  • Ali Özen  · 技术社区  · 7 年前

    我试图得到欧元,美元和土耳其里拉货币,并比较它们。但有时api(我使用的是随机货币网站json值)无法响应。 无法获取任何值和页面加载30秒,执行时间完成后,出现错误。 我要做的是:如果它不能在1秒(或更短)内从api中获取任何值,则返回null。我怎么能那样做。如果有人能帮忙,我会很高兴的。这是我的php代码。我试过用if-else,但没用。

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

    编辑

    $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;
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   JRoss    7 年前
    $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

    除此之外,我还会捕捉异常。 try {} catch (Exception $e) {}