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.