0

这是为该文件创建和强制下载 csv 文件。

这项工作,但我需要知道它是否以正确的方式进行。

公共函数 exportCSV($results){

    try {

        $filename = CSV_PATH.'file.csv';

        $numRows = count($results);

        $handle = fopen($filename, 'w+')  or die("can't open file");

        fputcsv($handle, array('id','name','age','address'));

        foreach ($results as $row) {

            fputcsv($handle, $row);
        }

        fclose($handle);

        header('Content-Disposition: attachment; filename="'.basename($filename).'"');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($filename));
        header('Connection: close');
        readfile($filename);
        exit();

    } catch(Exception $e) {
        echo $e->getMessage(); 
    }
}

CSV_PATH 位于 config.php 文件中

4

1 回答 1

0
   use  string rather then file writing it causes lot of overhead. 
   $out = "";
   $out .= implode(",", array('id','name','age','address')) . "\r\n";

   foreach ($results as $row) {
       $out .= implode(",", $row) . "\r\n";
    }

现在做同样的事情。

....
header('Connection: close');
echo $out;
于 2013-10-03T08:01:47.180 回答