PHP导出到CSV类

时间:2015-04-29 12:38:59

标签: php csv

我编写了以下类来将数据库结果导出为CSV文件。

<?php
class Export {
    public static function tocsv($results = array(), $fields = array()) {
        $schema_insert = '"'.implode('","', $fields).'"';
        $out .= $schema_insert."\n";

        foreach($results as $row) {
            $schema_insert = '';
            $schema_insert .= '"'.$row->week_ending.'",';
            $schema_insert .= '"'.$row->project.'",';
            $schema_insert .= '"'.$row->employee.'",';
            $schema_insert .= '"'.$row->plots.'",';
            $schema_insert .= '"'.$row->categories.'"';
            $out .= $schema_insert."\n";
        }
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . strlen($out));
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$filename");
        echo $out;
        exit;
    }
}
?>

输出结果为:

"Week ending","Project name","Plot numbers","Categories","Employee"
"Friday 08 May 2015","Big Road","Tracey Smith","1A, 2A, 3A"," Water meter, 1st fix inc lagging"

然而,当我用Excel打开时,所有内容都在一列中。我错过了什么吗?

感谢。

1 个答案:

答案 0 :(得分:1)

使用分号作为你的fieldterminator而不是逗号,它实际上是Excel的东西,而不是php的东西。