Download a CSV in PHP…use ob_clean()!

There are many blog posts, guides, code snippets and stackoverflow answers that describe how to create and download a CSV file in PHP.

Anyway none of them helped me the last time I was asked to do that in the context of the configuration panel of a PrestaShop module.

The problem was that I kept on getting the page constructed by the framework instead of the correct content of the file.

This was related to the fact that before reaching the point where I actually download the CSV, the PHP output (i.e. php://output) was polluted by the page created by the framework.

Here how I solved it:

private function exportCSV($report_data)
  {
    ob_clean();
    header("Content-type: text/csv");
    header("Cache-Control: no-store, no-cache");
    header("Content-Disposition: attachment; filename='{$this->csv_filename}'");

    $fp = fopen('php://output', 'w');

    foreach ($report_data as $key => $value) {
      fputcsv($fp, $value, ',', '"');
    }

    fclose($fp);
    die();
  }

The function is called after a normal form submission but the “magic” resides right in the ob_clean() call. This indeed clears the output buffer giving the possibility to output and obtain what needed.

P.S: please forgive the die() at the end 😛

Leave a Reply

wpDiscuz