0

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

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

4

1 回答 1

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");
于 2012-10-11T14:54:41.417 回答