Created
June 30, 2011 00:52
-
-
Save jcartledge/1055395 to your computer and use it in GitHub Desktop.
CSV -> SQLite
This file contains hidden or 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 | |
$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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.