Search code examples
phpcsvfgetcsvfputcsv

Read and write using fgetcsv and fputcsv


I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.

So I am taking that main source file then reading and putting the data in a "PROPER" csv file.

The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".

My code

$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
  foreach ($data as $item) {
     // echo $item;
     fputcsv($fh, array($item));
  }
}
$string = ob_get_clean();

$filename = 'csv_' . date('Ymd') .'_' . date('His');

// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");

exit($string);

Any help is highly appreciated. Thanks in advance.


Solution

  • Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:

    header("Content-Disposition: attachment; filename=\"$filename.csv\" );