0

I am trying to create a import tool that would read the csv file and allow me to map it to a the table columns and import it. I am trying to do this using code igniter.

Has anyone does this and have a library or is there a tool available in php and/or codeigniter. I wanted to check before I try to reinvent the wheel.

John Conde
  • 217,595
  • 99
  • 455
  • 496
kanhaic
  • 103
  • 2
  • 5
  • [dbutil](http://codeigniter.com/user_guide/database/utilities.html#csv) helps you to convert db data into csv format. This will help you for _export_ functionality. There is no CI library for _import_. [This](http://stackoverflow.com/questions/11337221/codeigniter-rest-csv-import-to-mysql) may help you in that case – Bhuvan Rikka Oct 11 '12 at 14:46

1 Answers1

2

I did something similar a long time ago, I'm feeling generous so here is a code snippet! :-)

I have the user select the appropriate fields from a form on the front end, but you can always hard code this in if your CSV file never changes.

Obviously you will want to modify to your needs (delimiters, field names, etc...) but this should get you started in the right direction.

// get POST values
$objPost = (object) $this->input->post('arr_of_fields');

$fh_csv = fopen('YOUR CSV FILE');
$fh_tmp = fopen('YOUR TEMP FILE');

while( false !== ($line = fgets($fh_csv)) )

    $enclosed = ''; // or whatever your field is enclosed with
    $delimiter = ','; // or whatever your delimiter is

    $columns  = explode($enclosed.$delimiter.$enclosed, trim($line, $enclosed));

    // the $objPost->field_X signifies the index for that field [0,1,2,3,+++]
    $data = array(
       'field_1' => trim(@$columns[@$objPost->field_1], $enclosed),
       'field_2' => trim(@$columns[@$objPost->field_2], $enclosed),
       'field_3' => trim(@$columns[@$objPost->field_3], $enclosed),
       'field_4' => trim(@$columns[@$objPost->field_4], $enclosed),
    );

    // write line to temp csv file, tab delimited with new line
    $str = implode("\t", $data) . "\n";

    @fwrite($fh_tmp, $str); // write line to temp file
}
@fclose($fh_csv);
@fclose($fh_tmp);

// import from temp csv file into database
$sql    = sprintf("LOAD DATA LOCAL INFILE '%s'
            INTO TABLE `%s`
            FIELDS TERMINATED BY '\\t'
            LINES TERMINATED BY '\\n'
            (field_1, field_2, field_3, field_4)",
            "TEMP FILE",
            "DATABASE TABLE NAME");

$query  = $this->db->query( $sql );

// delete temp file
@unlink("TEMP FILE");
Petar Zivkovic
  • 970
  • 10
  • 20