Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 14 revisions

Category:Libraries::CSV

[h3]CSV Formatted Data Reader[/h3]

This is a utility class built to support my own strategy for multilingual and translation management as explained in the [url=http://www.codeigniter.com/Wiki/LangBuilder]LangBuilder[/url] entry.

But I'm sure you'll find other kind of usage...

[h3]Requirements[/h3]

  • CI: tested on 1.5.3
  • PHP: tested on 5.2.1

[h3]The library code[/h3]

[code]<?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.

  • Let's consider the following CSV formatted data:

  •    col1;col2;col3 
    
  •     11;12;13
    
  •     21;22;23
    
  • It's returned as follow by the parsing operations:

  •     Array(
    
  •         [0] => Array(
    
  •                 [col1] => 11,
    
  •                 [col2] => 12,
    
  •                 [col3] => 13
    
  •         )
    
  •         [1] => Array(
    
  •                 [col1] => 21,
    
  •                 [col2] => 22,
    
  •                 [col3] => 23
    
  •         )
    
  •    )
    
  • @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; } }

?> [/code]

Clone this wiki locally