Created
June 4, 2014 18:21
-
-
Save taichunmin/1a5912f8bed5c615c7bb to your computer and use it in GitHub Desktop.
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
<?php | |
/* | |
2012/11/07 taichunmin First Release | |
Make SQL file from a TAB separate file. | |
*/ | |
function tai_tab2sql($filein, $fileout, $tbl = '') | |
{ | |
$fin = fopen($filein, 'r'); | |
$fout = fopen($fileout, 'w'); | |
if( !$fin || !$fout ) die('In tai_tab2sql(): Can not open file.'); | |
// 處理 field name | |
$line = stream_get_line($fin, 1000000, PHP_EOL); | |
$schema = explode("\t",$line); | |
var_export($schema); | |
$fieldCnt = count($schema); // 儲存長度 | |
$schema = @array_map('trim',$schema); | |
$schema = @array_map('mysql_escape_string',$schema); | |
$schema = implode('`,`',$schema); | |
fwrite($fout, "insert into `$tbl` (`$schema`) values \n"); | |
$pComma = false; | |
while( $line = stream_get_line($fin, 1000000, PHP_EOL) ) | |
{ | |
if($line=='')break; | |
$data = explode("\t", $line); | |
if(count($data) != $fieldCnt) | |
{ | |
die("field count does not match. Please re-check input file."); | |
} | |
$data = @array_map('mysql_escape_string',$data); | |
$data = implode("','",$data); | |
if($pComma) fwrite($fout, ","); | |
else $pComma = true; | |
fwrite($fout, "('$data') \n"); | |
} | |
fclose($fin); | |
fclose($fout); | |
system("notepad \"$fileout\""); | |
} | |
$op = 'y'; | |
do | |
{ | |
fprintf(STDOUT, "File in name -> "); | |
$filein = stream_get_line(STDIN, 1000000, PHP_EOL); | |
fprintf(STDOUT, "File out name -> "); | |
$fileout = stream_get_line(STDIN, 1000000, PHP_EOL); | |
fprintf(STDOUT, "Table name -> "); | |
$tbl = stream_get_line(STDIN, 1000000, PHP_EOL); | |
tai_tab2sql($filein, $fileout, $tbl); | |
fprintf(STDOUT, "Exit Program? [y/n] -> "); | |
fscanf(STDIN, " %s", $op); | |
}while($op!='Y' && $op!='y') | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment