允许在Codeigniter中下载CSV文件

时间:2017-07-20 06:18:14

标签: php codeigniter csv

这里有一些从数据库表中提取的数据。现在我想将所需数据下载为csv,并要求用户下载csv文件。

我的AJAX文件已创建,但主要问题是,它不会要求用户下载该文件。

以下是点击导出按钮时执行的$.ajax({ url:"<?php echo site_url('Customer/ExportCsv'); ?>", type: 'post', data: { userId: userId }, success:function(data){ alert(data); } }); 代码

public function ExportCsv(){     
    $csvdata=array('customer_name','customer_email', 'customer_mobile','birth_date', 'marriage_date','address','status');//Column headers        
    // fetch the data
    $query = $this->db->get_where('customer', array('user_id' => $_POST['userId'],'is_deleted' => '0'));
    //$this->db->order_by("create_date", "desc");
    $getRes = $query->result_array();

    $csv = "ID,Customer Name,SenderId,UserID,Receiver Number,ReceiverID,Message Content,Send Date,Status,Message Length,Message Type,RequestID,FailureMsg \n";//Column headers

    foreach ($getRes as $record){
        $csv.= $record['customer_name'].','.$record['customer_email'].','.$record['customer_mobile'].','.$record['birth_date'].','.$record['anniversery_date'].','.$record['address'].','.$record['status']."\n"; //Append data to csv
    }

// output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=Yourdata.csv');

    $csv_handler = fopen('php://output', 'w');            
    fwrite ($csv_handler,$csv); //Write headers and data
    fclose ($csv_handler);  //Close CSV file connections
}

这里是我的控制器功能

(person1)-[:LIKES]->(person2)

请指导我哪里出错..!感谢

2 个答案:

答案 0 :(得分:0)

我的AJAX只有一点点改变,而且有效:)

SharedPreferences

答案 1 :(得分:0)

请按照以下步骤操作:

第1步:

$header_name=array('customer_name','customer_email','customer_mobile','birth_date','marriage_date','address','status');//Column headers

// fetch the data
    $query = $this->db->get_where('customer', array('user_id' => $_POST['userId'],'is_deleted' => '0'));
    $getRes = $query->result_array();

第2步:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Type: application/vnd.ms-excel'); 
header("Content-Disposition: attachment; filename=filename.csv");

第3步:

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

// output the column headings
fputcsv($output,$header_name);

// loop over the rows, outputting them
$finalData = array();

$fp = fopen('file.csv','w');

第4步:

foreach( $getRes as  $data)
{

    $finalData[]=$data['customer_name'];
    $finalData[]=$data['customer_email'];
    $finalData[]=$data['customer_mobile'];
    $finalData[]=$data['birth_date'];
    $finalData[]=$data['marriage_date'];
    $finalData[]=$data['address'];
    $finalData[]=$data['status'];

    fputcsv($output, $finalData);
    unset($finalData);
} 

第5步:

fclose($fp);