1

how can I force the browser to download a csv file I created in PHP?

I tried

$result = array (
   array('aaa', 'bbb', 'ccc', 'dddd'),
   array('123', '456', '789'),
   array('aaa', 'bbb')
);

$filename = 'result_file.csv';

header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Length: " . strlen($result));
echo $result;
exit;

but the csv file is full of PHP errors

4
  • your in no way creating a csv file - i don't understand why you think that would work Commented May 6, 2014 at 3:14
  • Should I, or shouldn't I... @Dagon Let the OP figure it out, or pop in an answer... oh what to do. lol After all, it's a simple fix. Commented May 6, 2014 at 3:52
  • @Fred-ii- flee in horror was my response ;-) Commented May 6, 2014 at 4:06
  • I put in a plug for ya @Dagon ;-) Commented May 6, 2014 at 4:10

1 Answer 1

8

Here you go, compliments of Dagon and myself.

<?php

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$data = array(
   array('aaa', 'bbb', 'ccc', 'dddd'),
   array('123', '456', '789'),
   array('aaa', 'bbb')
);

outputCSV($data);

function outputCSV($data) {
    $output = fopen("php://output", "w");
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.