Tutorials

Reading CSV File in CodeIgniter

Mar 17, 2009 insic 61 Comments

codeigniter csv
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

Then supposing we have a CSV file that contains data like this.

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.

Next open system/application/views create a new file name it csv_view.php and populate the code below.

Thats how easy reading CSV data using CI. Add some styling and you can have like this.

table data

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. :)

About the author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

  • http://www.benoitvilliere.com Ben

    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!

  • http://www.pushingbuttons.net Timothy

    Awesome! I’ve dealt with CSVs before, and it can prove to be a real pain. This will come in handy. Thanks.

  • Eduardo

    very cool girl!keep creating tutorials pn CodeIgniter ;)

  • http://www.noginn.com Tom Graham

    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

  • http://www.benoitvilliere.com Ben

    I wasn’t aware of this. Thanks Tom. PHP has always some nice functions to deliver when needed!

  • http://twitter.com/hostingsearch Eva Vesper

    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.

  • http://www.taotedesign.com Vincent Le Pes

    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 :)

  • Pingback: Read CSV File With CodeIgniter

  • http://www.twenstudio.com Twenstudio

    Thanks you and nice tutorial

  • http://www.iloveyouwp.com wordpress themes

    thanks awesome sir!

  • http://www.twenstudio.com Twen

    Thanks

  • RandiR

    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

  • http://chergaoui.com Ahmed

    Was looking for a simple way to explain how to use the Csvreader class, and that’s it!
    Thank you for this mini tutorial!

  • http://twitter.com/saurabhshah saurabh shah

    Nice post insic … very simple one than other posts …

  • Misha

    Any idea about parsing huge CSV files (let’s say around 200MB)? How could we modify the library to handle those?

    Thanks!

  • daniel

    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

  • http://blog.insicdesigns.com insic2.0

    @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.

  • Daniel

    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?

  • http://blog.insicdesigns.com insic2.0

    Try this print_r($csvData) in your view, and see if you can find “id” or maybe it is “Id”.

  • Daniel

    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.

  • http://www.joseduenas.com Jose Duenas

    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.

  • ata

    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,

  • kazuya

    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)? :D

    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

  • http://twitter.com/k00k k00k

    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.

  • http://blog.insicdesigns.com insic2.0

    @kOOk thanks for pointing that out.

  • http://twitter.com/k00k k00k

    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.

  • arnold

    Finally I found some good tutorials for CodeIgniter!keep it up

  • http://farinspace.com Dimas

    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

  • http://brianseitel.com Brian

    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”,
    [email protected]”, “Joe Schmoe”, “555 Main St., Apt 100″,
    [email protected]”, “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,
    [email protected], Joe Schmoe, 555 Main St.,
    Apt 100, [email protected], 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

  • atheeq

    How to export the data to excel sheet. Kindly help me..

  • http://www.newdailyblog.blogspot.com tahsin

    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

  • http:/www.bname.ru/ Alexander Osipov

    Thanks for this library, it very useful for me!)

  • http://cebufreelancer.com mandoy

    is this CSV library capable to handling large csv data like 800MB or more ?

  • http://www.turpeau.net/pierrejean/ pjturpeau

    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*

  • Biggs

    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

  • Fatih

    thank you for the tutorial.
    do you know any class, library or sth. to export these CSVs to a pdf file??

  • peterXP

    That’s grete tutorial!

    But It’s difficult for newbie to store file&foloder in where?
    You should point path file to show to newbie.

    error say
    “Message: file(./csv/products.csv) [function.file]: failed to open stream: No such file or directory
    Filename: libraries/csvreader.php”

  • http://www.exclusivetutorials.com Exclusive Tutorials

    thanks for this

  • zohaib

    nice

  • http://jchancafe.posterous.com/ Johnny

    en el ejemplo hay un error:
    la cabecera del archivo .csv debe ser igual al que se esta usando al leer el arreglo.
    archivo.csv:
    Id,Name,Category,Price

    en csv_view.php:

  • Ravi

    good tutorial dude. it will help a lot

  • Tom

    Thank you for this great tutorial. We use CSV files to import data from one system to another. I was struggling getting this library to work but now it seems to be working correctly!

  • http://twitter.com/javierdaniel Dano

    Thanks for sharing.

    I’m not sure why you did not use fgetcsv for this?
    http://php.net/manual/en/function.fgetcsv.php

    Regards,

  • Allan

    Its working, thanks…

    Can you please give me a hint on how can I add the pagination class on this library?

  • http://www.nashie.net Steven Nash

    Hi,

    I am trying to use this class but I am getting a lot of errors like this:

    “A PHP Error was encountered

    Severity: Notice

    Message: Undefined index: prodid

    Filename: views/feed.php

    Line Number: 30″

    I am trying to work out what the problem is and it would be useful if you bundled the class with a sample CSV that definitely worked, that way I could be absolutely certain whether the problem was my spreadsheet rather than the code or implementation.

    • http://blog.insicdesigns.com insic

      Try dumping your $data and see if there is an index of an array named prodid , sometimes a csv has double quote in the index.

  • Nitesh

    THanks. THis tutorial Helps me.

  • noisyboy

    thanks it works, i made some modification line 52 to work in php 5 “$elements = explode($this->separator, $line);”
    and line 61 “$item[trim($field)] = $elements[$id];” to remove white space on the array..

    thanks

  • Frank

    Looks fine, didn’t test the code.
    I’m using an old class for the same purpose, this one looks quite short and good.
    CSV is still in use, that’s definitely, especially if you have dislocated data, different programs and/or platforms that is using data etc.etc.

  • copikeyc

    Thanks for the tutorial. It help me a lot :)
    also thanks to noisyboy for the tweaks >:D

  • http://roseavery.tumblr.com/ Beau Vazquez

    Please tell me something about How to use csv file in codeigniter?

  • Andy

    thanks for the tutorial, really help me :)

  • Shnaya

    Function split() is deprecated

    • Hira Sharker

      just replace it(split) with explode! it will work fine

  • Pingback: Awesome tutorials to master CodeIgniter | CatsWhoCode.com

  • Safan Momin

    Great tuts! i do have 1 question though, how do i import this or any csv into my database after i has been uploaded using mysql and codeigniter. Thanks again

    • Hira Sharker

      if ur csv is in preferred format like exact field name existing in your mysql table, THEN u can use foreach($csvData as $field) { $this->db->insert(‘table_name’,$field); } in ur model ……
      But if u just want to store csv files with any format then only u can store is the link of ur uploaded csv link!!!!

  • Pingback: Tutorials to master CodeIgniter | YoursCircle

  • Rinku

    Thanks a lot dude

  • http://www.programmingdesk.blogspot.com Kabir Hossain

    I am trying to upload a csv file after then the file data
    will be print/insert.But my code is not printing the data according to
    my code.It is printing Id: Marks complete 1.But my file is uploading.
    my input csv file format is

    Id,Marks
    20,46
    20,46
    32,45

    My controller code is

    public function upload_marks(){
    $config['upload_path'] = ‘./uploads/’;
    $config['allowed_types'] = ‘csv’;
    $config['max_size'] = ’10000′;

    $this->load->library(‘upload’, $config);
    if ( ! $this->upload->do_upload(‘marksfile’))
    {
    echo $this->upload->display_errors();
    }
    else
    {
    $uploadData = $this->upload->data();
    $fileName = $uploadData['file_name'];
    $this->load->library(‘csvreader’);
    $csvData = $this->csvreader->parse_file(‘./uploads/’,$fileName);
    foreach($csvData as $data){
    echo ” ID: “.$data['id'];
    echo ” Marks: “.$data['marks'];
    }
    echo ” Complete 1″;
    }
    }

    Where is the problem ? Could you get my error ?