Skip to content

Instantly share code, notes, and snippets.

@boudra
Created October 5, 2016 08:17
Show Gist options
  • Save boudra/f196f85e6a541760eb43945c1884da47 to your computer and use it in GitHub Desktop.
Save boudra/f196f85e6a541760eb43945c1884da47 to your computer and use it in GitHub Desktop.
Convert a CSV file with a header to a CREATE + INSERT sql script
<?php
$file = $argv[1];
$table_name = $argv[2];
$lines = file($file);
$header = array_shift($lines);
$fields = str_getcsv(trim($header));
$fields = array_map(function($field) {
$field = str_replace(' ', '_', $field);
$field = preg_replace('/[^A-z_]/', '', $field);
$field = strtolower($field);
return $field;
}, $fields);
for($i = 0; $i < count($fields); $i++) {
$count = array_count_values($fields)[$fields[$i]];
while($count-- > 1) {
$j = count($fields) - array_search($fields[$i], array_reverse($fields)) - 1;
$fields[$j] = $fields[$j] . '_' . $count;
}
}
$fields = implode("," . PHP_EOL, array_map(function($field) {
return "`$field` VARCHAR(100)";
}, $fields));
echo "CREATE TABLE `$table_name` ($fields);";
foreach ($lines as $line) {
$values = str_getcsv(trim($line));
echo sprintf('INSERT INTO `%s` VALUES ("%s");', $table_name, implode('","', $values)) . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment