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

 

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

 

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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值