Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Created April 23, 2017 10:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohwaz/b1b6796561628e80e2a4381fe32b098a to your computer and use it in GitHub Desktop.
Save bohwaz/b1b6796561628e80e2a4381fe32b098a to your computer and use it in GitHub Desktop.
Import CSV file in a SQLite table, including column headers
<?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