Excel CSV helper for CodeIgniter

Download csv_helper.zip (updated on February 4, 2008)

array to csv

$array = array(
	array('Last Name', 'First Name', 'Gender'),
	array('Furtado', 'Nelly', 'female'),
	array('Twain', 'Shania', 'female'),
	array('Farmer', 'Mylene', 'female')
);
 
$this->load->helper('csv');
echo array_to_csv($array);
"Last Name","First Name",Gender
Furtado,Nelly,female
Twain,Shania,female
Farmer,Mylene,female

Direct download

array_to_csv($array, 'toto.csv')

query to csv

$this->load->database();
$query = $this->db->get('my_table');
 
$this->load->helper('csv');
echo query_to_csv($query);

Direct download

query_to_csv($query, TRUE, 'toto.csv')

Feedback

Hey can you please help me get the titles for array to csv. I wanna use the array keys as the title (like they do in the query to csv). Can you please tell me how to do it with your helper? mmarcus44@gmail.com
Michael
Feb 25, 2009
#1
This was a big help to get me going, thanks! In the future I may add in the CI Download Helper usage if anything. @Michael and for anyone else: You can use array_keys and array_values if you need to pull out those pieces of information as a "regular" array with numeric indexes.
Joshua
May 4, 2009
#2
Searching something like this. Thanks Joshua for this great help. :-D
Russel
Jul 28, 2009
#3
Thanks for this helper. It saved me a lot of work and it's very robust and yet simple to use. I truly appreciate it. Keep up the good work mate!
Rick C.
Sep 21, 2009
#4
//function that convert an object to an array was useful for mi function objectToArray( $object ) { if( !is_object( $object ) && !is_array( $object ) ) { return $object; } if( is_object( $object ) ) { $object = get_object_vars( $object ); } return array_map( 'objectToArray', $object ); } //hope it helps
uoL
Nov 11, 2009
#5
Hi can i use this helper and call directly the model function and export it to csv? Thanks please send me to coder5@ymail.com
coder5
Jan 12, 2010
#6
Beautifully simple, and still works!! Thank you
RJ
Jan 17, 2010
#7
thank you, very simple and very very useful..
Az
Feb 7, 2010
#8
Thaks for your helper, it's very simple to use and very useful.

Bur i wonder if i can export the data in a xls format directly. Currently (i implemented this into a client's application), my client has to export the data, open excel, choose import data from file, and select comma separated value.

Anyway, amazing simple helper.

Thanks again
Jesus
Feb 23, 2010
#9
great

I use this

amazing


mahrizal
Apr 29, 2010
#10
great

I use this

amazing
Crazy Huy
May 20, 2010
#11
Many thanks! Very handy, saves quite a bit of time! :)
Ethan
Jun 10, 2010
#12
Thanks for this helper.But I have some problem when I convert to csv file my session have been not exist I want my session to be alive. How I can do?.
KayZ
Jul 6, 2010
#13
compress output = FALSE

otherwise you will loose hours trying to see where the problem starts
one2one
Aug 2, 2010
#14
This method exhausts an unusually high amount of RAM and does not work for me for anything over 1,500 lines or so. Any ideas to fix it?
NexusRex
Aug 8, 2010
#15
Here's how I'm using it:

// Export all locations for the specified account
// Will provide a CSV file to download
function export_all($id) {
$this->config->set_item('compress_output', FALSE);
$this->load->helper('csv');

// Get all locations
$query = $this->locations_m->get_all($id);
$this->db->select('*');
$this->db->from('locations');
$this->db->where('account_id', $id);
#$this->db->limit(1000);

$query = $this->db->get();
#$array = $query->result_array();

query_to_csv($query, TRUE, 'export_all.csv');
}
NexusRex
Aug 8, 2010
#16
I receive an error when I use the array_to_csv function

This webpage is not found.

No webpage was found for the web address:
12Bo
Dec 7, 2010
#17
It doesn't seem to like the stdClass Object being used as the array. Any thoughts on resolving this issue?

12Bo
Dec 7, 2010
#18
Works like a charm! Nice work and thanks for sharing with the community.
Roger
Dec 30, 2010
#19
I am trying to exports csv/xls using this helper.

That works fine with every browsers except IE. Every time i export csv files it resets IE session.

Any help will appreciable.
Russel
Jan 16, 2011
#20
Very nice :)
Sunbni
Jan 25, 2011
#21
Thanks man!!!.

Very useful.
Taytus.com
Jan 31, 2011
#22
$%$%#$%#%
yes ,it can work,but when it export a chinese record to a .csv file, they are the wrong characters like that '#%#%%@#'.Why? What can i do? waiting for Online!!!!
Eric
Feb 15, 2011
#23
thanks..
successfull
neoryzer
Feb 15, 2011
#24
Hi bit of a glitch for me.

my query is as follows

"
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '@');
$query = $this->db->get('Membership');
return $query->result();
"

I would like the csv file to contain only two fields, ID and Email.

How would I go about that?
Jon York
Mar 24, 2011
#25
Nevermind, Got it, just had to use select commands!
jon york
Mar 24, 2011
#26
HOW CAN I FIX THE COLUMN SIZE OF CSV FILE ...?
TANIM
Apr 18, 2011
#27
there's an error A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/csv/system/application/models/csv_model.php:27)

Filename: helpers/csv_helper.php

Line Number: 27

i dont know how to solve it..please help me guys!! thanks a lot in advance
kristine
May 2, 2011
#28
Same issue here with the headers... I disabled the profiler, and I don't have anything else being sent to the browser that I know of. Help?
dsheetz
May 16, 2011
#29
I used .htaccess to set output_buffering to on, and it worked.

Only problem I'm having now is that there's a bunch of carriage returns at the top of the file... anyone else experiencing this?
dsheetz
May 16, 2011
#30
Very userful. Thanx
Pablo
Jun 9, 2011
#31
Had written my whole code and then stumbled on this one. Ended up using this one !!!! nice work.
Shikhar
Jun 17, 2011
#32
hi,, can i set the delimiter with this helper??
ibnu
Jul 26, 2011
#33
Thanks ... Its very usefull ..
Linzay Mughal
Aug 11, 2011
#34
when send the csv to file too send the html file
Roberto Estupiñán Pérez
Oct 18, 2011
#35
Thanx...its very usefull for me..

but how to set delimiter with ";" ?
bradercep
Jan 28, 2012
#36
al revez? como importo?
refer
Feb 7, 2012
#37
This is so helpful! Thank You So Much!!! <3
Jowie
Feb 16, 2012
#38
for separate with ";" or another delimiter, in the line

if ( ! fputcsv($f, $line))

add

if ( ! fputcsv($f, $line, ';'))

or whatever delimiter you need (;

jose damian garrido munoz
Mar 13, 2012
#39
When i try to downlaod a file using this helper, it asks for username and password
How can i fix it.
Please help me, im stuck for one week in this.
Regards
Rai
Mar 16, 2012
#40
Amazing, thanks for sharing,

great!!
shameed
Apr 5, 2012
#41
Thank you for the helper. Is there any helper for importing excel or csv file in Codeigniter?
Programmer
Apr 15, 2012
#42
Great helper indeed
Thanks!
Muse
May 10, 2012
#43
THANKS FOR THE EFFORT OF SHOWING THIS CODE TO US . IT'S A GREAT HELP..GOD BLESS U
FERDIE
Jun 6, 2012
#44
AMAZING! THANKS A LOT!
Cesar
Aug 20, 2012
#45
I have a bit of a problem why is it appending the page source? I posted the full question here http://stackoverflow.com/questions/12178739/why-is-excel-csv-helper-for-codeigniter-appending-page-source

Any help would be appreciated.
Ryan Gannon
Aug 29, 2012
#46
Sweet! Thank you :)
David
Sep 19, 2012
#47
hi
to export query to csv using one table its working fine. i need to be export sum other table in same csv file. how to do that.any buddy can help me.
mouna
Nov 9, 2012
#48
great article, thank you so much...
Jalal khan
Nov 16, 2012
#49
Hi.. Thanks for this.. It was really helpful :)
Purvi
Nov 20, 2012
#50
Updated the code to work with UTF characters for excel on both Mac and Windows by converting all UTF-8 characters into UTF-16 LE.

http://cloud.pixls.co/LIk4


&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
* CSV Helpers
* Inspiration from PHP Cookbook by David Sklar and Adam Trachtenberg
*
* @author Jérôme Jaglale
* @link http://maestric.com/en/doc/php/codeigniter_csv
*/

// ------------------------------------------------------------------------

/**
* Array to CSV
*
* download == "" -> return CSV string
* download == "toto.csv" -> download file toto.csv
*/
if ( ! function_exists('array_to_csv'))
{
function array_to_csv($array, $download = "")
{
if ($download != "")
{
/*
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset=UTF-8');
//header('Content-Type: application/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $download . '"');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
*/

header('Content-Description: File Transfer');
//header('Content-Type: application/octet-stream');
header("Content-Type: application/vnd.ms-excel; charset=UTF-16LE");
header('Content-Disposition: attachment; filename='.$download);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo "\xEF\xBB\xBF"; // UTF-8 BOM
echo "\xFF\xFE"; // UTF-16 LE
}

ob_start();
$f = fopen&#40;'php://output', 'w'&#41; or show_error("Can't open php://output");
$n = 0;
foreach ($array as $line)
{
$n++;
if ( ! fputcsv($f, $line, "\t"))
{
show_error("Can't write line $n: $line");
}
}
fclose($f) or show_error("Can't close php://output");

$str = ob_get_contents();




ob_end_clean();

//UTF-16LE support
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');

if ($download == "")
{
return $str;
}
else
{
echo $str;
}
}
}

// ------------------------------------------------------------------------

/**
* Query to CSV
*
* download == "" -> return CSV string
* download == "toto.csv" -> download file toto.csv
*/
if ( ! function_exists('query_to_csv'))
{
function query_to_csv($query, $headers = TRUE, $download = "")
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('invalid query');
}

$array = array();

if ($headers)
{
$line = array();
foreach ($query->list_fields() as $name)
{
$line[] = $name;
}
$array[] = $line;
}

foreach ($query->result_array() as $row)
{
$line = array();
foreach ($row as $item)
{
$line[] = $item;
}
$array[] = $line;
}

echo array_to_csv($array, $download);
}
}

/* End of file csv_helper.php */
/* Location: ./system/helpers/csv_helper.php */
email@williamli.hk
Dec 2, 2012
#51
it's work!!.. thanks a lot.
rizki
Dec 6, 2012
#52
hi.. i've been using your helper but it does not create line break in each end of the line.. pls help me.. thank you..
dom
Dec 12, 2012
#53
Thank you very much for this helper
Laurent Partal
Dec 17, 2012
#54
Thanks! this was very helpful
Renji
Jan 21, 2013
#55
what about importing csv to mysql
nikz
Feb 7, 2013
#56
This is an awesome helper and a freaking time saver! Thanks for the download, it's extremely appreciated.
Jorge
Feb 26, 2013
#57
great article, thank you so much...

one question for how to save csv file in my project folder
plz help me i am beginner in codeInighter .so send me solution by mail . my mail Id is Rahul.owc@gmail.com . plz as soon as

again i told great article, thank you so much...

regard
Rahul
Rahul Dubey
Mar 3, 2013
#58
Thank you - I have not found a tool so easy to implement and use and so pragmatic in a long time. It addresses a very common need in an extremely elegant and efficient way.

KUDOS!

I have a profile online - May I please provide a link to this site in my "Special Thanks" section?? Let me know and I would be delighted to get your work shared!
Shaun Ryan
Mar 13, 2013
#59
[HELP]
I backup data with this csv_helper.php
but when import with csvreader.php, why there is code like this "ï» ¿"
Mustopa
Mar 20, 2013
#60
Here we need to create csv file first. Is there any way with out creating file directly download csv file
Pramod
May 8, 2013
#61
i had problem in server.


A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /home/content/42/10979942/html/admin/application/controllers/report/report.php:1)

Filename: helpers/csv_helper.php

Line Number: 28
chithrangan
Jun 6, 2013
#62
formatting issue ... in Office 365, Excel with a MacBook Pro.
shailendra
Jun 14, 2013
#63
Hi,

Thanks for sharing!

No support for Russian characters, was fixed http://cloud.pixls.co/LIk4 shared by the user "email@williamli.hk"!

Please update your codebase with this, or share it in github, would be nice!

Thanks!
Helder
Jul 1, 2013
#64
Here is codeigniter excel helper to download data into xls format

&lt;?php
/**
* export mysql data or any kind of data in to xls format.
* @param $fields: Name of Headers
* @param $result_array: Data to be put into excel
* @param $filename: name of download file
* @author shankar kumar
* @return download xls file
*/
function convert_into_excel($fields=array(),$result_array=array(),$filename='simple')
{
$headers = ''; // just creating the var for field headers to append to below
$data = ''; // just creating the var for field data to append to below
$i=0;
foreach ($fields as $field)
{

$headers .= $field . "\t";


}
$k=1;
if($result_array)
{
foreach ($result_array as $row)
{
$line = '';
$m=1;
foreach ($row as $value)
{
if ((!isset($value)) or ($value == ""))
{
$value = "\t";
}
else
{
if($m==1)
{
$value = '"' . $k . '"' . "\t";
}
else{
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
}
$line .= $value;
$m++;
}
$data .= trim($line) . "\n";
$k++;
}

}
$data = str_replace("\r", "", $data);

header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=$filename.xls");
echo "$headers\n$data";
}


?&gt;
shankar
Aug 16, 2013
#65
I need to convert my php codeigniter to excel format. i dont know how to use the above code.
plz help me...
Bharathi
Aug 19, 2013
#66
I have used array_to_csv but its not working after processing blank page came..no csv genrated.
help please
rohit
Sep 30, 2013
#67
if you are getting blank page probably you are passing and object not an array.
avandaro
Nov 25, 2013
#68
how to set the width size in each row.please guide me.
siddiq
Dec 26, 2013
#69
thank you very much!. great helpfully us!

once again thank you
rajaram
Jan 29, 2014
#70
thanks it seems to work helpful
Gopi nath dhara
Apr 8, 2014
#71

A PHP Error was encountered

Severity: Warning

Message: fopen&#40;&#41; [function.fopen]: Filename cannot be empty

Filename: helpers/csv_helper.php

Line Number: 14
An Error Was Encountered

Can't open php://output
amit
Apr 25, 2014
#72
pl tell me how can i increase width of columns using this helper also tell how to format csv file
sumit joshi
Jul 23, 2014
#73
It works perfectly! But I have a question. How do I insert column header? Thank you
John
Nov 4, 2015
#74
when i download , Why failed network ???
but i can play internet
Attapong
Dec 17, 2015
#75
Hi,

need to filter out one categorie from result.
Help??

TNX
Moriaty
Jan 30, 2016
#76
thanks, it works :)
johnnie
Mar 10, 2016
#77
in angularjs $http url calling does not work
if the the same url of $http pasted into url it's working in file..
please help
ravi mane
Apr 20, 2016
#78
i means when ajax rquest does not work
same url pasted in browser url field its work
ravi mane
Apr 20, 2016
#79
Hallo, welche Datenbank daten muss ich denn in der config/Database.php eintragen?
ichbins
Jul 15, 2016
#80
Hi,
I am using this method in my codeigniter project. My data contains unicode characters. but it didn't export properly. here is my code :

$result = $this->Reports_model->ExportReportSummary($logID);
$delimiter = ",";
$newline = "\r\n";
$filename = "Report-".date('d-m-Y').".csv";
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);

I tried several solutions, but all fails. someone please help me to resolve this issue
eliz
Sep 13, 2017
#81