Reading CSV File in CodeIgniter

A Comma separated values (CSV) file is a computer data file used for implementing the tried and true organizational tool, the Comma Separated List. The CSV file is used for the digital storage of data structured in a table of lists form, where each associated item (member) in a group is in association with others also separated by the commas of its set. Each line in the CSV file corresponds to a row in the table. Within a line, fields are separated by commas, each field belonging to one table column. Read more about this file format here.
There is a handy library available in CodeIgniter framework which is the CSVReader that will makes reading or parsing CSV formatted data easily.
In this article, I try to show you how to use it. But since this library is not included in CodeIgniter package you need to add this to your system/libraries directory.
Create a new file in your system/libraries directory named it to csvreader.php. Go here and download the code.
The CSVReader Class
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CSVReader Class
*
* $Id: csvreader.php 147 2007-07-09 23:12:45Z Pierre-Jean $
*
* Allows to retrieve a CSV file content as a two dimensional array.
* The first text line shall contains the column names.
*
* @author Pierre-Jean Turpeau
* @link http://www.codeigniter.com/wiki/CSVReader
*/
class CSVReader {
var $fields; /** columns names retrieved after parsing */
var $separator = ','; /** separator used to explode each line */
/**
* Parse a text containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_text($p_Text) {
$lines = explode("\n", $p_Text);
return $this->parse_lines($lines);
}
/**
* Parse a file containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_file($p_Filepath) {
$lines = file($p_Filepath);
return $this->parse_lines($lines);
}
/**
* Parse an array of text lines containing CSV formatted data.
*
* @access public
* @param array
* @return array
*/
function parse_lines($p_CSVLines) {
$content = FALSE;
foreach( $p_CSVLines as $line_num => $line ) {
if( $line != '' ) { // skip empty lines
$elements = split($this->separator, $line);
if( !is_array($content) ) { // the first line contains fields names
$this->fields = $elements;
$content = array();
} else {
$item = array();
foreach( $this->fields as $id => $field ) {
if( isset($elements[$id]) ) {
$item[$field] = $elements[$id];
}
}
$content[] = $item;
}
}
}
return $content;
}
}
Then supposing we have a CSV file that contains data like this.
Id,Name,Category,Price 1,iPhone,Mobile,300, 2,iMac,Desktop,529, 3,MacBook,Mobile,2000, 4,iTouch,Gadgets,157, 5,Wii,Gaming,1250,
What is our aim here is read the data form the CSV file then present it in a tabular form in an html table.
Supposing you have a clean install CI in your development server. Go tosystem/application/controller folder and open the welcome.php file and add the function below.
function index()
{
$this->load->library('csvreader');
$filePath = './csv/products.csv';
$data['csvData'] = $this->csvreader->parse_file($filePath);
$this->load->view('csv_view', $data);
}
Next open system/application/views create a new file name it csv_view.php and populate the code below.
<table cellpadding="0" cellspacing="0">
<thead>
<th>
<td>PRODUCT ID</td>
<td>PRODUCT NAME</td>
<td>CATEGORY</td>
<td>PRICE</td>
</th>
</thead>
<tbody>
<?php foreach($csvData as $field){?>
<tr>
<td><?=$field['id']?></td>
<td><?=$field['name']?></td>
<td><?=$field['category']?></td>
<td><?=$field['price']?></td>
</tr>
<?php }?>
</tbody>
</table>
Thats how easy reading CSV data using CI. Add some styling and you can have like this.

After writing this short tutorial, I realized that this may not be helpful in any way. I dont know why I came up with that stupid thought. Maybe for the reason CSV is quite old data format? And maybe no one is using this right now? hmmm tell me what you think about it. Anyway I still posting it hoping it will help someone.


17. Mar, 2009 








I think it’s always cool to have this kind of article available at one click. That’s not un-useful like you said
For instance, you could use this script to import your Gmail contacts to a database. I like the fact you’re into Codeigniter, I started using it a while ago, and I think it’s cool you write about it, you help promoting it, which is good for the hole CI community
Please don’t stop!
Awesome! I’ve dealt with CSVs before, and it can prove to be a real pain. This will come in handy. Thanks.
very cool girl!keep creating tutorials pn CodeIgniter
PHP already has a built in function for parsing CSV files, the CI class seems a little over kill.http://uk3.php.net/manual/en/function.fgetcsv.php
I wasn’t aware of this. Thanks Tom. PHP has always some nice functions to deliver when needed!
Well, I thought it was a useful because I didn’t even know anything about CSV. =)
Btw, how we contact you? I don’t see a contact form but I could be crazy.
I find it quite useful; if, for example, you had an Excel spreadsheet, you could easily output it as a CSV and create a clean version for your site using our method
Thanks you and nice tutorial
thanks awesome sir!
Thanks
I use biterscripting for processing CSV files – usually stock price tables, either from web sites or history files on my computer. It is very helpful. They have a very good sample script at http://www.biterscripting.com/SS_WebPageToCSV.html . This script extracts a table (based on a table number) from a web page (based on a URL) and stores it in CSV format. To try, download biterscripting (it is free), then install their sample scripts using the following command.
scr “http://www.biterscripting.com/Download/SS_AllSamples.txt”
Randi
Was looking for a simple way to explain how to use the Csvreader class, and that’s it!
Thank you for this mini tutorial!
Nice post insic … very simple one than other posts …
Any idea about parsing huge CSV files (let’s say around 200MB)? How could we modify the library to handle those?
Thanks!
Hi is a nice tutorial. I am a beginner in PHP and I don’t know where to put the csv folder and file in the structure of codeigniter.
Is the application folder considered the root folder?
This is the error I get:
Severity: Warning
Message: file(./csv/products.csv) [function.file]: failed to open stream: No such file or directory
Filename: libraries/csvreader.php
Line Number: 59
@daniel where did you put the csv directory? And no the application folder is not the root folder. the root is where your index.php located, it is outside the application folder.
Ok I got it was a problem with the path of the CSV now I got a new error:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id
Filename: views/csv_view.php
Line Number: 14
I did all the steps in the tutorial above. I run PHP 5 on the server is this a problem?
Try this print_r($csvData) in your view, and see if you can find “id” or maybe it is “Id”.
Ok I got it it was a problem of case sensitive variable. I also used the CSV example above and it needed an , after the last item:
Id,Name,Category,Price,
Thanks for help it works now very nice stuff and easy.
It’s not unuseful at all. Thanks for the tutorial. I’ve done a project with CSV format a few months agoso the CSV format is not dead still.
Hello, i have a problem, the library return this:
Array
(
[0] => Array
(
[Id] => 1
[Name
] => peter
)
[1] => Array
(
[Id] => 2
[Name
] => cindy
)
)
do you see the breakline in the last key ?
this is my problem
Message: Undefined index: Name
My csv:
Id,Name
1,peter,
2,cindy,
hi!
nice tutorial! i’m just new here,i mean using CI and PHP.
by the way,i have some question regarding on how to
export HTML Table ouput to excel(i hope you dont mind)?
for example: when a user click a search button based on its query
then the result will ouput in HTML Table,
and then there’s export button that will
export HTML Table ouput to excel.
or you can give me some links about this.
i tried to use Excel Plugin of codeigniter but i have no idea how to get
the data from HTML Table.
tnx
Please note, the code in the Csvreader.php library on the wiki that u link to differs from the one you have embedded in the blog entry here. Your embedded one behaves as I expected it to, by putting key => value pairs. The other one doesn’t, it just put all columns as one value (comma sep). Hope that makes sense and helps someone.
@kOOk thanks for pointing that out.
In playing with it a bit more, I believe that the only difference between the 2 (aside from comments) is the var $separator. In your example it’s set to comma, in the wiki version it’s set to semicolon. I think that’s what was giving me the unexpected behavior and that makes sense.
On another note, I had a weird issue with a \n newline character on my first line (descriptor) where I had data like so:
firstfield, secondfield
1234, a
4432, a
3434, a
3499, a
My last array element for the first line (secondfield) ended up having a newline character at the end of it like this:
array ([firstfield], [secondfield
])
This caused errors when trying to insert into a db. Long story short, the fix that worked in my case (YMMV) was to trim() all of the array elements. I added a line to the parse_lines() function like so:
Right after the line:
$elements = split($this->separator, $line);
add this line:
$elements = array_map(‘trim’, $elements);
For me, this successfully got rid of the unwanted newline character that was plaguing my last descriptor name.
Hope that helps someone else.
Finally I found some good tutorials for CodeIgniter!keep it up
CSV / TSV are always useful, its usually the default for data exports. However I don’t see that this class supports a column enclosure such as a quote, like PHP fgetcsv function does.
123,Gdata Page,”google, gdata, api”,http://www.google.com
Hiyas. I’ve been using your CSVReader thing for awhile now, and I’ve run into one error that I haven’t been able to reconcile. I don’t know much about regex, so I’m not entirely sure how to go about fixing this.
Let’s imagine I’m using a CSV file with addresses that looks like this:
“Email”,”Name”,”Address”,
“joe@gmail.com”, “Joe Schmoe”, “555 Main St., Apt 100″,
“bob@gmail.com”, “Bob Jones”, “555 Main St., Apt 101″
I know that Excel and other spreadsheet apps set each value within quotes, but your reader doesn’t take this into account. Your CSVReader would divide it up like this:
Email, Name, Address,
joe@gmail.com, Joe Schmoe, 555 Main St.,
Apt 100, bob@gmail.com, Bob Jones
555 Main St., Apt 101, (null)
Does that make sense?
Basically, the problem I’m running into is that some of my addresses have commas in them, and since CSVReader is just delimiting by commas and not determining if they’re in a value (set aside by double quotes), then it’s throwing off the entire database.
Can you help? I’ve spent two or three hours trying various solutions and I’m not any closer than I was before.
Thanks a ton!
B
How to export the data to excel sheet. Kindly help me..
nice post, but php provides a function named fgetcsv. So, we don’t need to write so much code. See my code for uploading a csv file here on http://www.newdailyblog.blogspot.com
thanks.
tahsin
Thanks for this library, it very useful for me!)
is this CSV library capable to handling large csv data like 800MB or more ?
It seems my amateurish code snippet has success here. FYI, I have updated the code to use the more reliable fgetcsv() function. It shall resolve most problems people have encountered here.
Refer to http://codeigniter.com/wiki/CSVReader/
*cheers*
Just tried this for my bank statement.csv file (HSBC).
My data is like this:
2010-01-12,A DESCRIPTION OF TRANSACTION,-34.90
First, I got the wiki version of the library which pjturpeau links to above. Then I had to change in the class var $separator from semicolon to comma. Finally the table in the view code above was a bit messed up, but that was fixed by removing the <thead>, <th> and <tbody> tags.
Perfect! All I have to do now is figure out how to get this data into a database table.
Thanks for this tutorial, very much appreciated.
Biggs
thank you for the tutorial.
do you know any class, library or sth. to export these CSVs to a pdf file??