CodeIgniter Forums
CSV PHP Parser - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=22)
+--- Thread: CSV PHP Parser (/showthread.php?tid=32666)



CSV PHP Parser - El Forum - 07-30-2010

[eluser]Unknown[/eluser]
I didn't have any luck parsing different variations of comma-delimited CSV files using the current CI Libraries (or one instance of LOAD DATA INFILE), but then I discovered this Google Code Project. Use the DataSource.php file as your library file.

The Libary file is attached as a .txt; just change the extension and you're good to go!
Example Controller:
Code:
<?php
class TestException extends Exception {}

class Test extends User_Controller {
       public function __construct() {
           parent::__construct();
    }
    
    //<-----------------------------------begin test----------------------------------&gt;

    public function test() {
        $this->load->library('DataSource');
        $csv = new File_CSV_DataSource;
        $csv->load('path');
        $headers=$csv->getHeaders();
        print_r($headers);
        if ($csv->isSymmetric()) {
            $array = $csv->connect();
        } else {
              //fetch records that dont match headers length
            $array = $csv->getAsymmetricRows();
        }
        print_r($array);
        //or go json crazy
        echo json_encode($array);
    }
    
    //<-----------------------------------end test----------------------------------&gt;

}
?&gt;