Pergunta

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

Foi útil?

Solução

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);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top