manjusha manjusha - 3 months ago 62
PHP Question

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.

Answer

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) {
                fputcsv($handle, $data);
            }
                fclose($handle);
            exit;
        }
}