使用codeigniter进行csv文件导入和映射的最佳方法是什么

时间:2012-10-11 14:31:26

标签: php codeigniter csv import etl

我正在尝试创建一个导入工具来读取csv文件并允许我将其映射到表列并导入它。我正在尝试使用代码点火器。

有没有人这样做并拥有一个库或者有一个工具可用于php和/或codeigniter。在我尝试重新发明轮子之前,我想检查一下。

1 个答案:

答案 0 :(得分: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");