如何在php中将一个巨大的进程分成多个步骤?

时间:2012-11-20 12:55:53

标签: php database execution-time multi-step

我需要处理一个xml文件并相应地将一些数据插入到我的数据库中。由于XML文件包含接近10000行,并且可能有数千行要插入数据库,我担心我的脚本将超过max execution time

我已经看到一些脚本可以防止这种情况,他们将整个过程分成更小的步骤,脚本每隔几秒刷新一次页面,并继续执行任何操作。

我只是想知道它是如何完成的?

3 个答案:

答案 0 :(得分:1)

这是使用缓冲区的另一种解决方案:

set_time_limit(0);
header('Content-type: text/html; charset=utf-8');

echo 'Starting... <br />';
for ($i = 0; $i < 10; $i++) {   
    echo $i . '<br />';

    ob_flush(); 
    flush(); 

    sleep(1);
}
echo 'Finished. <br />';

我已将set_time_limit(0)(将超时设置为“无限”)以防万一。 header('Content-type: text/html; charset=utf-8')是必要的。这适用于Firefox和Chrome,但不适用于IE。如果我让它在IE上工作,我会更新。

更新1:您也可以通过命令行(CLI)调用脚本:

  • Windows(cmd.exe):php.exe -f \path\to\file.php
  • Unix(终端):php -f /path/to/file.php

在这些情况下,缓冲区不是必需的(因为没有浏览器,它们会抛出错误)。在这两种情况下,您都可以通过PHP exec启动该过程,但是您需要将日志写入某个文件,因为它不会输出到浏览器。

答案 1 :(得分:0)

我之前使用一个连续的索引变量重新调用了php页面。

步骤是:

1. start the script with no querystring. it will insert 1000 rows for this time. 
   (insert_bulk.php)
2. recall the script with data start index 1001.
   (insert_bulk.php?start=1001)
3. when the data finishes, stop recalling the script. 

这样可以防止溢出最大执行时间,并告诉您当前正在处理的部分。

答案 2 :(得分:-2)

您可以尝试在脚本中尝试睡眠()。 似乎它不算作执行时间(for linux servers only