Skip to content

Instantly share code, notes, and snippets.

@taichunmin
Created June 4, 2014 18:21
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 taichunmin/1a5912f8bed5c615c7bb to your computer and use it in GitHub Desktop.
Save taichunmin/1a5912f8bed5c615c7bb to your computer and use it in GitHub Desktop.
<?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