0
votes

I'm working on a form which creates a CSV file and then should display the download link. It's working well but does not output the success message due to the buffer termination.

File which generates the CSV File and the echo which is not but should be displayed:

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

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

    echo "Report created!";
}

This problem occurs after the following code from the object MyFlight_createCSV() which generates the CSV file and needs a ob_end_clean() in the beginning and ob_end_flush() in the end.

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();

By deactivating the ob_end_clean(); and ob_end_flush(); it's still working but gets a warning (cannot modify header information). To continue to output a success message after the CSV generation I tried several things like ob_start, redirect to another page etc. but nothing works and the output stay empty. Does anyone has an idea?

Best regards,

Lukas

1

1 Answers

0
votes

There is no reason to set the HTTP headers if you are writing the data into the file and not to the output.

You should separate the link generation (form generation) and the output of the CSV to the client, they cannot be done both in the same request.

For example (serving directly to the output instead of creating a file):

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
}