dst67283 2012-03-09 05:42
浏览 63
已采纳

php url数据获取在特定时间停止

I am using php 5.2 and I am fetching data from url using file_get_contents function. This is loop for 5000 and I have divided into 500 slots and set a script like this. For 500 it is taking 3 hours to complete because for some url it is taking too much time and for some it is in 1 sec that is fine.

What I want if url is taking more than 30 sec then skip and go for next. I want to stop fetch after 30 sec.

    <?php
// Create the stream context
$context = stream_context_create(array(
    'http' => array(
        'timeout' => 1       // Timeout in seconds
    )
));

// Fetch the URL's contents
echo date("Y-m-d H:i:s")."
";
$contents = file_get_contents('http://example.com', 0, $context);
echo date("Y-m-d H:i:s")."
";
// Check for empties
if (!empty($contents))
{
    // Woohoo
//    echo $contents;
echo "file fetched";
}
else
{
echo $contents;
echo "more than 30 sec"; 
}
?>

I have already done that it is not working for me because file_get_contents function is not stoping it will continue , then only thing now I am getting no result after 30 sec but time it is taking sameas u can see in output. Output of php

2012-03-09 11:26:38 2012-03-09 11:26:40 more than 30 sec

  • 写回答

2条回答 默认 最新

  • doutu1939 2012-03-09 05:46
    关注

    You can set the HTTP timeout. (Not tested)

    <?php
    $ctx = stream_context_create(array(
        'http' => array(
            'timeout' => 30
         )
    ));
    file_get_contents("http://example.com/", 0, $ctx); 
    

    Source

    Edit: I don't know why it isn't working with this code by you. But if you don't manage it to bring it to work with this you may also want to give CURL a try. This could be eventually also faster for that (but I don't know if that is really faster...).
    If that would work for you, you could than use the curl_setopt function to set the timeout time with the CURLOPT_TIMEOUT flag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号