Created
April 23, 2017 10:52
-
-
Save bohwaz/b1b6796561628e80e2a4381fe32b098a to your computer and use it in GitHub Desktop.
Import CSV file in a SQLite table, including column headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$fp = fopen($argv[1], 'r'); | |
$db = new SQLite3($argv[1] . '.sqlite'); | |
$db->exec('BEGIN;'); | |
$header = null; | |
$i = 0; | |
while (!feof($fp)) | |
{ | |
$line = fgetcsv($fp, 4096); | |
if (!$line) | |
{ | |
continue; | |
} | |
if (!$header) | |
{ | |
$header = $line; | |
$db->exec(sprintf('CREATE TABLE data (%s);', aggregate($header))); | |
continue; | |
} | |
$db->exec(sprintf('INSERT INTO data (%s) VALUES (%s);', aggregate($header), aggregate($line))); | |
echo $i++ . " lines\r"; | |
} | |
echo "\nCommiting..."; | |
$db->exec('COMMIT;'); | |
echo " Done.\n"; | |
fclose($fp); | |
function aggregate(Array $fields) | |
{ | |
return implode(', ', array_map('escape', $fields)); | |
} | |
function escape($str) | |
{ | |
global $db; | |
return sprintf('\'%s\'', $db->escapeString($str)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment