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

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 to system/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.

reading-csv-file-in-codeigniter

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.

 

Leave a Reply