Skip to content

Instantly share code, notes, and snippets.

@nckg
Created September 28, 2012 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nckg/3799388 to your computer and use it in GitHub Desktop.
Save nckg/3799388 to your computer and use it in GitHub Desktop.
Creates a SQL file with a simple sql `insert` statement from a .csv
#!/usr/bin/env php
<?php
setlocale(LC_ALL, 'nl_BE.UTF8');
$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
array_pop($data);
array_walk($data, 'wrapItem');
$sql[] = 'INSERT INTO src_leaseplandb VALUES (' . implode(', ', $data) . ');';
}
file_put_contents("import.sql", implode("\n", $sql));
/**
* Wraps an item in a wrapper ""
*
* @param $item mixed Item value
* @param $key mixed Item key
* @param $wrapper string The wrapper for the item
* @param $mysqlEscape bool Should we escape the item for db handling?
*/
function wrapItem(&$item, $key, $wrapper = '"', $mysqlEscape = FALSE)
{
$template = '%1$s%2$s%1$s';
if ($mysqlEscape == TRUE) {
$item = sprintf($template, $wrapper, mysql_real_escape_string($item));
} else {
$item = sprintf($template, $wrapper, str_replace('"', '\"', $item));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment