Загрузка CSV в SQLITE


#!/usr/bin/env php
<?php

define('SEPARATOR',";");
define('FIELD_LEN',300);
define('TABLE_NAME', 'table1');

function db_connect($dbfile='') {
    static $db = null;
    static $dbname = null;
    if ($db===null && $dbname===null) {
        $db = new PDO('sqlite:'.$dbfile);
        $dbname = $dbfile;
    }
    return $db;
}

function create_table($fields) {
    $db = db_connect();
    $sql = array();
    foreach($fields as $f) {
        $sql[] = $f.' VARCHAR('.FIELD_LEN.')';
    }
    $sql = 'CREATE TABLE IF NOT EXISTS '.TABLE_NAME.' ('.implode(',',$sql).');';
    $db->exec($sql);
}

function insert_row($row) {

    $db = db_connect();
    $key = array();
    $val = array();
    foreach($row as $k=>$v) {
        $key[] = $k;
        $val[] = $db->quote($v);
    }
    $sql = 'INSERT INTO '.TABLE_NAME.
           '('.implode(',',$key).') VALUES ('.implode(',',$val).');';
    $db->exec($sql);
}

if ($argc!=6) {
    echo $argv[0]." <field_count> (donames|getnames) (no1st|1st) <file> <database>\n";
}
else {

    $field_count = $argv[1];
    $field_names = $argv[2];
    $load_first = $argv[3];
    $file = $argv[4];
    $dbname = $argv[5];
    
    $db = db_connect($dbname);
    $c = 0;
    if ($f=fopen($file,'r')) {
        $h = array();
        while($d = fgetcsv($f,0,SEPARATOR)) {
            $c++;
            if ($c==1) {
                for($i=1; $i<=$field_count; $i++) {
                    if (!isset($d[$i-1])) $d[$i-1] = '';
                    if ($d[$i-1]=='' || $field_names=='donames')
                        $h[$i-1]='f_'.$i;
                    else
                        $h[$i-1] = $d[$i-1];
                }
                create_table($h);
                if ($load_first=='no1st') continue;
            }
            $r = array();
            for($i=1; $i<=$field_count; $i++) {
                if (!isset($d[$i-1])) $d[$i-1] = '';
                $r[$h[$i-1]] = $d[$i-1];
            }
            insert_row($r);
        }
        fclose($f);
    }

}

?>