使用PHP将查询结果保存到.csv

时间:2015-05-13 22:41:59

标签: php codeigniter export-to-csv

我运行了以下查询,我正在查看将数据导出到.csv或.xls文件的最佳方法。

<?php

    $channels = ee()->db->select('channel_titles.entry_id, channel_titles.title, channel_data.field_id_164')
    ->from('channel_titles')
    ->join('channel_data', 'channel_titles.entry_id = channel_data.entry_id')
    ->where(array(
            'channel_titles.channel_id' => '12',
        ))
    ->or_where(array(
            'channel_titles.channel_id' => '31',
        ))
    ->get();

    if ($channels->num_rows() > 0)
    {
        $i = 0;
        foreach($channels->result_array() as $row)
        {
            $i++;
            echo $row['field_id_164'].",".$row['title']."<br />\n";
        }
        echo $i;
    }       

?>

我尝试了一些方法,但似乎无法找出最佳选择。

1 个答案:

答案 0 :(得分:1)

经典的回声爆炸(&#39;,&#39;,$ col)等方式很好,但您也可以使用php的内置函数直接写入csv文件。

    $filename = 'test.csv';
    $file = fopen($filename,"w");
    if ($channels->num_rows() > 0) {
        foreach($channels->result_array() as $key => $row) {
            if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
            foreach ($row as $line) {
                $line = (array) $line;
                fputcsv($file, $line);
            }
        }
    }   

    fclose($file);

编辑:

如果您想立即下载/查看文件,您必须设置标题。

    $filename = 'test.csv';

    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
    header("Content-Transfer-Encoding: UTF-8");

    $file = fopen('php://output', 'a');
    if ($channels->num_rows() > 0) {
        foreach($channels->result_array() as $key => $row) {
            if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
            foreach ($row as $line) {
                $line = (array) $line;
                fputcsv($file, $line);
            }
        }
    }  

    fclose($file);