【问题标题】:reading a large file and forcing download读取大文件并强制下载
【发布时间】:2013-02-27 15:58:55
【问题描述】:
$name = 'mybigfile.csv';
    $fp = fopen(...);
    while($row = mysql_fetch_assoc($sql_result)) {
       fputcsv($fp, $row);
    }
    fclose($fp);



// send the correct headers
header("Content-Type: application/csv etc ....");
header("Content-Length: " . filesize($name));

// dump the file and stop the script
readfile($name);
exit;

这种方法效果很好,但有些文件很大,所以过程很慢......我在想 - 也许我可以避免先创建文件然后写入数据然后读取数据的过程并输出.... .i.e.如果我在 while 循环之前发送标头并在 while 循环中回显行(而不是将其写在一行中)或类似的东西。这会是更有效的过程吗?你会建议我如何改进这个过程?谢谢

【问题讨论】:

    标签: php csv


    【解决方案1】:

    直接写入输出:

    header("Content-Type: application/csv etc ....");
    
    while ($row = mysql_fetch_assoc($sql_result)) {
        fputcsv(STDOUT, $row);
    }
    

    参考这里:http://www.php.net/manual/en/wrappers.php.php

    【讨论】:

    • thx .. 在这种情况下创建文件是一种开销,我说得对吗?
    • 我收到此错误 - 消息:使用未定义的常量 STDOUT - 假定为“STDOUT”? ...我需要使用 .. php://stdout 吗? ...呃...我认为这 $stdout = fopen('php://stdout','w'); ...
    • 嗯,很奇怪。可能STDOUT 仅在命令行上定义和/或它可能取决于您的 PHP 配置。我不知道。但是,是的,使用fopen('php://output', 'w')(或php://stdout)打开流处理程序应该始终有效。
    • 是的,它与 fopen('php://output', 'w');而不是标准输出...谢谢您的帮助... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2012-12-31
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多