2012-10-11 92 views
0

我想創建一個導入工具,它將讀取csv文件,並允許我將它映射到表列並導入它。我正在嘗試使用代碼點火器來做到這一點。什麼是用codeigniter做csv文件導入和映射的最佳方法

有沒有人這樣做,並有一個庫或有一個工具在PHP和/或codeigniter可用。我想在嘗試重新發明車輪之前檢查一下。

+0

[dbutil](http://codeigniter.com/user_guide/database/utilities.html#csv)可以幫助您將db數據轉換爲csv格式。這將有助於您提供_export_功能。 _import_沒有CI庫。 [這](http://stackoverflow.com/questions/11337221/codeigniter-rest-csv-import-to-mysql)可能會幫助你在這種情況下 –

回答

2

很久以前我做了類似的事情,我感覺很慷慨,所以這裏是一段代碼片段! :-)

我讓用戶從前端的表單中選擇適當的字段,但是如果您的CSV文件永遠不會更改,您總是可以對其進行硬編碼。

顯然你會想修改你的需要(分隔符,字段名等),但這應該讓你開始朝着正確的方向發展。

// 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"); 
相關問題