Created
September 28, 2012 12:00
-
-
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
This file contains 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
#!/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