dqyat62284 2012-04-12 06:49 采纳率: 0%
浏览 95

为什么导出数据时下载窗口不会长时间出现在浏览器中

I try export data from database to .csv. When I click export link I don't see save window in browser for a very long time if there is quite a lot amount of data. It can be quite confusing if the script looks like hanging for some time and after quite a long time one can see save window in browser. The code is something like this in controller:

$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $fileName = $list->list_name . '.csv';

        $this->getResponse()->setHeader('Content-Type', 'text/csv; charset=utf-8')
                            ->setHeader('Content-Disposition', 'attachment; filename="'. $fileName . '"');      

        $contacts = new Contact();
        $contacts->export($listId);

Export method reads records one by one and prints it something like this:

    $fp = fopen('php://output', 'w');        
    foreach ($mongodbCursor as $subscriber) {
           $row = formRow($subscriber);
       fputcsv($fp, $row);
        }       

I see on some applications that save winow appear almost immediately and when you click save you see progress of downloading.

I tried to replace:

    $this->getResponse()->setHeader('Content-Type', 'text/csv; charset=utf-8')
                        ->setHeader('Content-Disposition', 'attachment; filename="'. $fileName . '"');

with this one:

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="'. $fileName . '"');

It didn't help so far. I wonder if it's possible to send headers before all data are read one by one from database? Thank your for your assistance.

  • 写回答

6条回答 默认 最新

  • douyanzhou1450 2012-04-12 06:56
    关注

    Hmm I'm not familiar with php://output, my application writes my information with fopen,fwrite,fclose to a temporary file afterwards I give it out with similiar header(); options.

                $filesize = filesize("tmp/export.csv");
                header("Content-Type: text/csv");
                header("Content-Disposition: attachment; filename=\"export.csv\"");
                header("Conent-Length: $filesize");
                readfile("tmp/export.csv");
                unlink("tmp/export.csv");
                exit;
    

    This one gives the download window of your browser instantly.

    评论

报告相同问题?