· 6 years ago · Aug 25, 2019, 03:22 AM
1<?php
2function import_csv_to_sqlite(&$pdo, $csv_path, $options = array())
3{
4 extract($options);
5
6 if (($csv_handle = fopen($csv_path, "r")) === FALSE)
7 throw new Exception('Cannot open CSV file');
8
9 if(!$delimiter)
10 $delimiter = ',';
11
12 if(!$table)
13 $table = preg_replace("/[^A-Z0-9]/i", '', basename($csv_path));
14
15 if(!$fields){
16 $fields = array_map(function ($field){
17 return strtolower(preg_replace("/[^A-Z0-9]/i", '', $field));
18 }, fgetcsv($csv_handle, 0, $delimiter));
19 }
20
21 $create_fields_str = join(', ', array_map(function ($field){
22 return "$field TEXT NULL";
23 }, $fields));
24
25 $pdo->beginTransaction();
26
27 $create_table_sql = "CREATE TABLE IF NOT EXISTS $table ($create_fields_str)";
28 $pdo->exec($create_table_sql);
29
30 $insert_fields_str = join(', ', $fields);
31 $insert_values_str = join(', ', array_fill(0, count($fields), '?'));
32 $insert_sql = "INSERT INTO $table ($insert_fields_str) VALUES ($insert_values_str)";
33 $insert_sth = $pdo->prepare($insert_sql);
34
35 $inserted_rows = 0;
36 while (($data = fgetcsv($csv_handle, 0, $delimiter)) !== FALSE) {
37 $insert_sth->execute($data);
38 $inserted_rows++;
39 }
40
41 $pdo->commit();
42
43 fclose($csv_handle);
44
45 return array(
46 'table' => $table,
47 'fields' => $fields,
48 'insert' => $insert_sth,
49 'inserted_rows' => $inserted_rows
50 );
51
52}