如何将数据从MySQL导出到csv文件并在CakePHP中下载?

时间:2018-07-19 18:38:07

标签: csv cakephp-2.0

这是从Mysql导出数据的代码。

$customers = $this->Customer->find('all',array('conditions'=>array('Customer.buyer_id'=>$id,'Customer.isDeposit' =>1,'Customer.isCancel' =>0),'order'=>array('Customer.id'=>'DESC')));


$output = fopen('php://output', 'w');
$delimiter = ",";
$fields = array('ID', 'Name', 'Email', 'Phone', 'Move Date', 'Status');
fputcsv($output, $fields, $delimiter);
if (count($customers) > 0) 
{
    foreach ($customers as $row) 
    {
        $lineData = array(
                                $row['Customer']['id'],     
                            $row['Customer']['first_name'] . ' ' . $row['Customer']['last_name'], 
                                $row['Customer']['email'], 
                                $row['Customer']['phone'], 
                                $row['Customer']['move_date'], 
                                (($row['Customer']['isCancel'] == 1) ? 'Cancelled' : 'Active')
                            );
                fputcsv($output, $lineData, $delimiter);
    }
}   

fseek($output, 0);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=Users.csv');
fpassthru($output);
exit;

但是,我无法像文件一样下载它。而是将数据打印在网页上。

enter image description here

如何强制将数据下载为文件?

我也尝试了此代码,但是下载的空白csv。

$this->layout = false;
$this->response->download("Users.csv");     
$this->set(compact('all_buyers'));      
Configure::write('debug','1');

0 个答案:

没有答案