minu
minu

Reputation: 73

How to export array to CSV in Codeigniter?

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

I want to export this array to CSV. I am using CodeIgniter.

Upvotes: 1

Views: 27324

Answers (6)

Antony
Antony

Reputation: 4364

Whilst yes, fputcsv is available it feels overkill even for the examples they provide (albeit the \n in my solution would negated).

The example below assumes Codeigniter 4 and uses the native headers option rather than the default PHP ones. implode() seems perfectly sufficient for basic array rows.

$this->response->setHeader('Content-Type','text/csv');
$this->response->setHeader('Content-Disposition','attachment; filename="'.$jobNo.'.csv"');

echo "\xEF\xBB\xBF"; // UTF-8 BOM

foreach ($list as $row){
    echo implode(',',$row)."\n";
}

Without the BOM (solution found here: How can I output a UTF-8 CSV in PHP that Excel will read properly?) this code didn't work but with it, my program (LibreOffice) correctly identified the content.

Upvotes: 0

MarcM
MarcM

Reputation: 2251

None of the previous answers were valid for me (for different reasons).

Thus, I created my own generic PHP function for it. It can be either included in a CodeIgniter helper (recommended), or as a private function of any CodeIgniter class, such as a Controller:

/*
 *  _array2csvstr()
 *  Array to string of comma-separated-values
 */

private function _array2csvstr(array $fields)
{
    $handler = fopen('php://memory', 'r+');
    if (fputcsv($handler, $fields) === false) {
        return false;
    }
    rewind($handler);
    $csv_string = stream_get_contents($handler);
    return rtrim($csv_string);
}

I take advantage of fputcsv() php function in memory, without the need of storing any file in the filesystem.

Upvotes: 0

NikuNj Rathod
NikuNj Rathod

Reputation: 1658

You can try this code for your export array to 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_array) {
                fputcsv($handle, $data_array);
            }
                fclose($handle);
            exit;
        }
}

I hope it will help you.

Upvotes: 14

TarangP
TarangP

Reputation: 2738

Best Use is use csv_from_result()

It Permits you to generate a CSV file from a query result. The first parameter of the method must contain the result object from your query.

$this->load->dbutil();

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

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

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

Upvotes: 0

Shakil Hossain
Shakil Hossain

Reputation: 1743

This Solution is working for me you have to call exportCSV Function with CodeIgniter controller

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; 
  }

Upvotes: 1

Nishit Patel
Nishit Patel

Reputation: 21

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;
    }

Upvotes: 2

Related Questions