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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

<?phpif(!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

*/

classCSVReader{

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

*/

functionparse_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

*/

functionparse_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

*/

functionparse_lines($p_CSVLines){

$content=FALSE;

foreach($p_CSVLinesas$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.

1

2

3

4

5

6

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 to system/application/controller folder and open the welcome.php file and add the function below.

PHP

1

2

3

4

5

6

7

8

9

10

functionindex()

{

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

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<table cellpadding="0"cellspacing="0">

<thead>

<th>

<td>PRODUCTID</td>

<td>PRODUCTNAME</td>

<td>CATEGORY</td>

<td>PRICE</td>

</th>

</thead>

<tbody>

<?phpforeach($csvDataas$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.

About The Author

Sean J is a web designer and developer. He currently is founder of designsave.com, a helpful blog where you can find free wordpress themes, graphic resources, best web tutorials and tips. When not in front of computer screen, he enjoys fishing, travelling and spending time with his Family.