导出sql到csv php codeigniter

wj8zmpe1  于 2023-01-28  发布在  PHP
关注(0)|答案(1)|浏览(111)

有人能帮我解决这个问题吗?
我有以下功能

public function exportcsv(){ 
    //echo 'hi'; exit();
   // file name 
    $filename = 'blocked_users_'.date('Y-m-d').'.csv'; 
    header("Content-Description: File Transfer"); 
    header("Content-Disposition: attachment; filename=$filename"); 
    header("Content-Type: application/csv; ");

   // get data 
    $user_data = $this->Common_model->get_users_for_csv();

   // file creation 
    $file = fopen($filename, 'w');

    $header = array("full_name", "phone", "email", "payment_method", "delivery_address", "delivery_city", "timestamp"); 
    fputcsv($file, $header);
    foreach ($user_data as $key=>$line){ 
        fputcsv($file,$line); 
    }
    fclose($file); 

    exit; 
}

文件生成2次,第一次在服务器根目录下,第二次下载到磁盘,但在服务器根目录下,文件头和内容正常,第二次下载到磁盘时,文件为空。

bxjv4tth

bxjv4tth1#

您应该删除行“fclose($file);“,因为在调用exit函数时文件已经关闭。

它应该工作:

public function exportcsv(){ 
    //echo 'hi'; exit();
   // file name 
    $filename = 'blocked_users_'.date('Y-m-d').'.csv'; 
    header("Content-Description: File Transfer"); 
    header("Content-Disposition: attachment; filename=$filename"); 
    header("Content-Type: application/csv; ");

   // get data 
    $user_data = $this->Common_model->get_users_for_csv();

   // file creation 
    $file = fopen(FCPATH.$filename, 'w');

    $header = array("full_name", "phone", "email", "payment_method", "delivery_address", "delivery_city", "timestamp"); 
    fputcsv($file, $header);
    foreach ($user_data as $key=>$line){ 
        fputcsv($file,$line); 
    }
    exit; 
}

**FCPATH -**它将给予项目根目录的完整路径

相关问题