Jaeger
Jaeger

Reputation: 1754

Issues with exporting a csv file

I'm creating a function that, when you click on a button, submits datas to a this function and in return, creates a .csv file and makes the browser download it. I followed the huge amount of tutorials that can be found online, but maybe I'm mixing up things:

header("Content-Type: application/x-excel");
header("Content-disposition: attachment; filename=export".date('d-m-Y') .".csv");
header('Expires : 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

$list = array
  (
    "Peter,Griffin,Oslo,Norway",
    "Glenn,Quagmire,Oslo,Norway",
  );

$file = fopen("contacts.csv","w");


foreach ($list as $line) {
    fputcsv($file,explode(',',$line));
}

die($file);

readfile($file);

Just keep in mind that these aren't my real datas, I just want to set everything up before continuing, because I have 50 lines of an array to handle.

With this code, If I keep die($file), the file gets downloaded but is empty. If I remove it, my browser tells me that the website is unavailable.

What am I missing?

Upvotes: 0

Views: 47

Answers (1)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

try this

header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
    "Peter,Griffin,Oslo,Norway",
    "Glenn,Quagmire,Oslo,Norway",        
);

$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

Upvotes: 1

Related Questions