Codeigniter,强制下载返回数据而非下载面板

时间:2018-04-03 04:34:44

标签: php codeigniter csv download

我想将数据从数据库导出到csv。这是我的代码

public function export_product_to_csv()
{
    $response = new stdClass();
    $response->success = TRUE;
    $response->message = "Terjadi kesalah saat proses export. Silakan hubungin administartor";
    $this->load->dbutil();
    $this->load->helper('file');
    $this->load->helper('download');
    $delimiter = ",";
    $newline = "\r\n";
    $filename = "list_item.csv";
    $query = "SELECT * FROM `list_item` ";
    $result = $this->db->query($query);
    $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
    $download = force_download($filename, $data);
    if ($download) {
        $response->message = "Export Berhasil ";
        $response->link = $this->generate_activity_link("view_product_management","Export Product");
        $response->success = TRUE;
    } else {
        $response->message = "Gagal . Query salah.";
    }
  return $response;   
}

但是当我执行代码时它会返回

  

" ITEM_ID"" ITEM_CODE"" TYPE_ID"" ref_number"" ITEM_NAME"&# 34;价格"" qty_perpack"" label_code"" CLIENT_ID" " 1"" RL30CM"" 5"" "," Pengaris 30 Cm"," 1500"," 150"," TX30CM"," 0&#34 ; " 2"," VP00"," 5",""," Ventplug dengan karet",&# 34; 2000"" 2000"" TXVP0"" 1" " 3"," PP Merah"," 1",""," Bahan coba"," ; 15000"""""" 0" " 4"" TNVA"" 5"" "," Antena Tv"," 15000"," 1000"," TXTVNA"," 2" " 5"," YZHAA"," 5","","测试barang"," ; 1500"&#34 1000"" TEST"" 2" " 6"," YHASA"," 5",""," Pengaris 20 Cm",&#34 ; 2000"" 1000"" UZYA"" 2" " 7"," PP Hitam"," 1",""," PP Hitam"," ; 15000"""""" 0" " 8"," PP002"," 1",""," Biji plastik hijau",&# 34; 200000"""" PPGR"" 2" " 9"," BBW"," 4",""," Bubble Wrapper"," 75000"""""" 0"

不下载面板。请帮帮我

1 个答案:

答案 0 :(得分:1)

使用此方法并根据您的要求进行排列。我已经多次使用它,它一直对我有用

//get records from database
$query = $db->query("SELECT * FROM list_item ORDER BY id DESC");

if($query->num_rows > 0){
    $delimiter = ",";
    $filename = "file_name_" . date('Y-m-d') . ".csv";

    //create a file pointer
    $f = fopen('php://memory', 'w');

    //set column headers
    $fields = array('ID', 'Name', 'Email', 'Phone', 'Created', 'Status');
    fputcsv($f, $fields, $delimiter);

    //output each row of the data, format line as csv and write to file pointer
    while($row = $query->fetch_assoc()){
        $status = ($row['status'] == '1')?'Active':'Inactive';
        $lineData = array($row['id'], $row['name'], $row['email'], $row['phone'], $row['created'], $status);
        fputcsv($f, $lineData, $delimiter);
    }

    //move back to beginning of file
    fseek($f, 0);

    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}