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

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

1

6 Answers 6

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

$data as $data, didn't it overwrite the prev variable?
@SahuVKumar Please look I have modified my answered.
2
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;
    }

Comments

1

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

Comments

0

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

1 Comment

Yes, I keep using this functionality but if need some alteration in data or formatting, its bit tricky to do right in the query itself.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.