1

我有一个函数可以连接到大约 1000 多个数据库并取回数据并将其放入数组中。

但是,数据太大了,我想在每次循环通过连接时在浏览器上显示结果,而不是等待整个循环完成。

或者如果有更好的方法,请分享。

function Get_data()
{
 // loop base on the number of available databases
    for ($i = 0; $i < count($client_databases); $i++) {

        // Getting connection for each database
        $database = $this->connect_clients_db($client_databases[$i]);

       // return an array of data from the database
        $ClientShema = $this->getSomeData($database);

        // put the data in array
         $schemas[]=$ClientShema;
    }


     return $schemas;


}

结果的例子是

loop 1 (database_one) 这是来自数据库一的数据

循环 2 (database_two) 这是来自数据库 2 的数据

4

1 回答 1

3

You can turn on output buffering and flush the buffer periodically to the browser.

First, you have to send a certain amount of data to the browser:

echo str_repeat(" ", 40000);

Next, you need to start output buffering:

ob_start();

Finally, after you've output what you want to send to the browser, you need to flush the output buffer. I found that I had to call the following three functions to get this to work:

ob_end_flush();
ob_flush();
flush();

So, your code might look like the following:

function Get_data()
{
    echo str_repeat(" ", 40000);

    //loop base on the number of available databases
    for ($i = 0; $i < count($client_databases); $i++) {
        //Start buffering output
        ob_start();

        // Getting connection for each database
        $database = $this->connect_clients_db($client_databases[$i]);

        // return an array of data from the database
        $ClientShema = $this->getSomeData($database);

        // put the data in array
        $schemas[]=$ClientShema;

        //Write some output somewhere here.

        //flush the output buffer here.
        ob_end_flush();
        ob_flush();
        flush();
    }

    return $schemas;
}

Here is a block of code you can use to test this technique:

<?php

echo str_repeat(" ", 40000);

for ($i = 0; $i < 10; $i++) {
    ob_start();

    echo "Hello world.<br/>";
    ob_end_flush();
    ob_flush();
    flush();

    usleep(500000);
}
于 2013-09-11T16:42:11.180 回答