通过PHP将CSV文件导入SQLite数据库

时间:2014-06-27 12:10:56

标签: php sql sqlite csv

我想通过PHP脚本将CSV文件中的表导入SQLite DB,我可以手动运行以更新数据。

下面列出了我想要实现的目标:

  1. 将旧表(称为“produkte”)重命名为product-currentdate(或删除表格)
  2. 然后从CSV文件导入文件(;分隔,ISO 8859-1字符集/ CSV文件的第一行包含表格标题)
  3. 将日期保存在表格“product”
  4. 我找到了一个由于某种原因无效的脚本:

    <?php
     $dir = 'sqlite:test.sqlite';
     $dbh  = new PDO($dir) or die("cannot open the database");
    
    
     $query = <<<eof
      LOAD DATA LOCAL INFILE 'produkte.csv'
      INTO TABLE produkte
      FIELDS TERMINATED BY ';'
      OPTIONALLY ENCLOSED BY '"' 
      LINES TERMINATED BY '\n'
      IGNORE 1 LINES 
      (id, Hauptmenue, Produktgruppe, Beschreibung, Text, Bild, Shop, Info)
    
     eof;
    
     $dbh->query($query);
    
    ?>
    

    我希望有人知道如何解决我的问题...

    最好的问候戴夫

1 个答案:

答案 0 :(得分:2)

Federico CingolaniGithub发布了符合您需求的php脚本

 <?php
function import_csv_to_sqlite(&$pdo, $csv_path, $options = array())
{
    extract($options);

    if (($csv_handle = fopen($csv_path, "r")) === FALSE)
        throw new Exception('Cannot open CSV file');

    if(!$delimiter)
        $delimiter = ',';

    if(!$table)
        $table = preg_replace("/[^A-Z0-9]/i", '', basename($csv_path));

    if(!$fields){
        $fields = array_map(function ($field){
            return strtolower(preg_replace("/[^A-Z0-9]/i", '', $field));
        }, fgetcsv($csv_handle, 0, $delimiter));
    }

    $create_fields_str = join(', ', array_map(function ($field){
        return "$field TEXT NULL";
    }, $fields));

    $pdo->beginTransaction();

    $create_table_sql = "CREATE TABLE IF NOT EXISTS $table ($create_fields_str)";
    $pdo->exec($create_table_sql);

    $insert_fields_str = join(', ', $fields);
    $insert_values_str = join(', ', array_fill(0, count($fields),  '?'));
    $insert_sql = "INSERT INTO $table ($insert_fields_str) VALUES ($insert_values_str)";
    $insert_sth = $pdo->prepare($insert_sql);

    $inserted_rows = 0;
    while (($data = fgetcsv($csv_handle, 0, $delimiter)) !== FALSE) {
        $insert_sth->execute($data);
        $inserted_rows++;
    }

    $pdo->commit();

    fclose($csv_handle);

    return array(
            'table' => $table,
            'fields' => $fields,
            'insert' => $insert_sth,
            'inserted_rows' => $inserted_rows
        );

}