如何在Codeigniter中将数组导出为CSV?

时间:2016-08-12 05:04:39

标签: php codeigniter csv

 $Data[] = array('x'=> $x, 'y'=> $y, 'z'=> $z, 'a'=> $a);

我想将此数组导出为CSV。我正在使用CodeIgniter。

4 个答案:

答案 0 :(得分:8)

您可以尝试将导出数组的此代码转换为CSV。

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Import extends CI_Controller {

        public function __construct() {
            parent::__construct();
        }
        public function exports_data(){
            $data[] = array('x'=> $x, 'y'=> $y, 'z'=> $z, 'a'=> $a);
             header("Content-type: application/csv");
            header("Content-Disposition: attachment; filename=\"test".".csv\"");
            header("Pragma: no-cache");
            header("Expires: 0");

            $handle = fopen('php://output', 'w');

            foreach ($data as $data) {
                fputcsv($handle, $data);
            }
                fclose($handle);
            exit;
        }
}

我希望它会对你有所帮助。

答案 1 :(得分:0)

function exportEtpCsv(){
        $data[] = array('f_name'=> "Nishit", 'l_name'=> "patel", 'mobile'=> "999999999", 'gender'=> "male");
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=\"test".".csv\"");
        header("Pragma: no-cache");
        header("Expires: 0");

        $handle = fopen('php://output', 'w');
        fputcsv($handle, array("No","First Name","Last Name"));
        $cnt=1;
        foreach ($data as $key) {
            $narray=array($cnt,$key["f_name"],$key["l_name"]);
            fputcsv($handle, $narray);
        }
            fclose($handle);
        exit;
    }

答案 2 :(得分:0)

此解决方案对我有用,您必须使用CodeIgniter控制器调用exportCSV Function

public function exportCSV(){ 
   // file name 
   $filename = 'users_'.date('Ymd').'.csv'; 
   header("Content-Description: File Transfer"); 
   header("Content-Disposition: attachment; filename=$filename"); 
   header("Content-Type: application/csv; ");
   
//    get data from mysql
//    public function ViewDataa($table, $sel) {
//    $this->db->select($sel);
//    $this->db->from($table);
//    return $this->db->get()->result_array();
//    } 

   $usersData = $this->am->ViewDataa("eml_collection", "name, email, phone, Areyouarealtor");
   
  // CSV header
   $header = array("Name","Email","Phone","Areyouarealtor"); 




$usersData   //Will your Data array  
   // file creation 
   $file = fopen('php://output', 'w');
   fputcsv($file, $header);
   foreach ($usersData as $key=>$line){ 
     fputcsv($file,$line); 
   }
   fclose($file); 
   exit; 
  }

答案 3 :(得分:0)

最佳使用是使用csv_from_result()

它允许您从查询结果生成CSV文件。方法的第一个参数必须包含查询的结果对象。

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

echo $this->dbutil->csv_from_result($query);

引用:https://www.codeigniter.com/user_guide/database/utilities.html#export-a-query-result-as-a-csv-file