将数据从php导出到csv

时间:2017-03-30 08:37:56

标签: php csv

我有一个php文件。此文件是Opencart中的Feed文件的副本,如下所示:

  <?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    foreach ($ids->rows as $id) {
    //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
    $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
    }

    $this->response->addHeader('Content-type: text/csv');
    $this->response->setOutput($myrow);
    }
    ?>

当我使用上面的代码,然后当我在浏览器中运行php文件时,我得到一个下载的php文件,其中包含我需要的所有数据。我的问题是如何以csv格式导出?

我尝试了来自http://code.stephenmorley.org/php/creating-downloadable-csv-files/的代码,但根本没有成功。有什么想法吗?

我也在某处阅读,我必须逃避单引号,双引号和逗号。我该怎么做?

编辑:

我也试过这个:

<?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    $fp = fopen('php://output', 'w');
 foreach ($ids->rows as $id) {
        //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
        $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
        fputcsv($fp, $myrow);
        }
fclose($fp);
 $this->response->addHeader('Content-type: text/csv');
         $this->response->setOutput($fp);
}
?>

没有成功!

1 个答案:

答案 0 :(得分:1)

我认为你没有告诉你的浏览器下载文件,为了解决这个问题,我刚刚告诉浏览器我们正在编写哪个文件。

// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"'); 
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');

// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');

// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));

// Sample data. This can be fetched from mysql too
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55'));

// output each row of the data
foreach ($data as $row)
{
 fputcsv($file, $row);
}

exit();