PHP - ob_end_flush() 后的输出

PHP - Output after ob_end_flush()

我正在处理一个创建 CSV 文件的表单,然后应该会显示下载 link。它运行良好,但由于缓冲区终止而没有输出成功消息。

生成CSV文件的文件和未显示但应显示的回显:

if(isset($_POST['createExport'])) {

    $export = new MyFlight_CreateCSV();
    $export->createCSV();

    echo "Report created!";
}

此问题发生在 object MyFlight_createCSV() 中的以下代码生成 CSV 文件并需要 ob_end_clean() 开头和 ob_end_flush () 到底。

ob_end_clean();

$fh = @fopen( $filename, 'w' );
fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-type: text/csv' );

fputcsv( $fh, $header_row );
foreach ( $data_rows as $data_row ) {
    fputcsv( $fh, $data_row );
}
fclose( $fh );

ob_end_flush();

通过停用 ob_end_clean();和 ob_end_flush();它仍在工作,但收到警告(无法修改 header 信息)。为了在 CSV 生成后继续输出成功消息,我尝试了几种方法,例如 ob_start、重定向到另一个页面等,但没有任何效果,输出保持为空。有人有想法吗?

此致,

卢卡斯

如果您将数据写入文件而不是输出,则没有理由设置 HTTP headers。

您应该将 link 生成(表单生成)和 CSV 输出到客户端分开,它们不能在同一个请求中完成。

例如(直接服务于输出而不是创建文件):

if(isset($_GET['ExportCSV']) {
  header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
  header( 'Content-Description: File Transfer' );
  header( 'Content-Disposition: attachment; filename="report.csv"');
  header( 'Content-type: text/csv; charset=utf-8' );
  $fh = fopen("php://output", 'w');
  fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) );
  fputcsv($fh, $header_row);
  foreach($data_rows as $data_row) {
    fputcsv($h, $data_row);
  }
  fclose($fh);
  exit;
} else {
  // output the form with the link mentioning ExportCSV=1 in the GET parameters
}