PHP CSV创建并强制下载

时间:2013-10-03 07:49:53

标签: php

这是针对该文件的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文件

1 个答案:

答案 0 :(得分: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;