Skip to content

Instantly share code, notes, and snippets.

@jcartledge
Created June 30, 2011 00:52
Show Gist options
  • Save jcartledge/1055395 to your computer and use it in GitHub Desktop.
Save jcartledge/1055395 to your computer and use it in GitHub Desktop.
CSV -> SQLite
<?php
$db = new PDO('sqlite:./my.sqlite');
$csv = fopen('my.csv', 'r');
$columns = strtolower(
str_replace(' ', '_',
preg_replace('/\r?\n$/', '',
fgets($csv)
)));
$db->query("CREATE TABLE table_name ($columns)");
while($row = fgetcsv($csv)) {
$row = implode(', ', array_map(function($val) {
return is_numeric($val) || preg_match('/^".*"$/', $val) ?
$val :
sprintf('"%s"', $val);
}, array_map(function($val) {
$date = strtotime($val);
return $date ? $date : $val;
}, $row)));
$db->query("INSERT INTO table_name ($columns) VALUES ($row)");
}
fclose($csv);
@jcartledge
Copy link
Author

The "quick and dirty" script I googled to do this was 80+ lines, so I wrote this instead. Bonus: converts date strings which PHP strtotime can parse to UNIX timestamps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment