Thursday, January 6, 2022

[FIXED] How to export array to CSV in Codeigniter?

Issue

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

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


Solution

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.



Answered By - NikuNj Rathod

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.