php://output 结果为空文件


php://output results in empty file

我有一个页面正在使用的Wordpress主题模板文件。该模板在数据库中查询数组,然后尝试将结果输出到 csv 文件。预计不会输出到浏览器。这是代码:

/***
 * Output an array to a CSV file
 */
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
    $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "w");
foreach($results as $result)
{
    fputcsv($outstream, $result);
}
fclose($outstream);
}

该文件按预期写入用户的下载目录,但它为空。我已经调试以验证是否有 117 个元素的结果。上面的循环正在执行。就好像输出缓冲区没有被刷新或被Wordpress清除一样。

你能

尝试使用:

$outstream = fopen("php://output", "a");

而不是:

$outstream = fopen("php://output", "w");