【问题标题】:if file_get_contents timeout, do something else如果 file_get_contents 超时,请执行其他操作
【发布时间】:2023-03-13 04:40:01
【问题描述】:

我有一段 file_get_contents 代码,它工作正常,但有时源 URL 没有响应,因此我的页面在 60 秒内没有加载(默认超时后)。 如果源 URL 在 5 秒内没有响应,我想为 file_get_contents 设置 5 秒超时以执行其他操作。 这是我的代码:

  <?php 
$url = 'https://www.example.com';
$content = file_get_contents($url);
$first_step = explode( '<div class="js-price-value">' , $content );
$second_step = explode("</div>" , $first_step[1] );
$second_step[0]= str_replace( " ", "",  $second_step[0]);
if (strlen(trim($second_step[0]))!==0) {
 $price=$second_step[0];

 echo $price;  

}else {
   echo '<div>something else</div>'
};
?>

在上面的代码之后我想要这样的东西:

if source url dose not respond in 5 seconds
{
do something else
}

【问题讨论】:

标签: php file-get-contents php-ini


【解决方案1】:

这就是你要找的:

file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));

源代码:Does file_get_contents() have a timeout setting?

将问题标记为重复删除。

【讨论】:

    【解决方案2】:

    我的回答: 以前看过这个话题 Does file_get_contents() have a timeout setting? 但这并不是我想要的。如果发生超时,我想做其他事情。 所以我使用了这段代码:

    $ctx = stream_context_create(array(
       'http' => array(
           'timeout' => 5
           )
       )
    );
    $url = 'source URL';
    $content = file_get_contents("$url", 0, $ctx);
    if(!$content){
       echo 'timeout happened';
    
    }elseif (another condition) {
       echo 'condition result'
    
    }else {
       echo 'something else'
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多