<?php

// -----------------------------
// GET RESSOURCES

set_time_limit(0);
ini_set('memory_limit''128M');

// -----------------------------
// CHECK AND DISPLAY HELP

if ( !$_SERVER['argv'][1] || empty($_SERVER['argv'][1]) ) {

    
$message = <<<EOM

        Usage: php tabtxt2mysqltable.php data/table1.dbf.txt
        Imports contents of the file into MySql.


EOM;
    die(
$message);
}

if ( !
is_file($_SERVER['argv'][1]) ) {

    
$message = <<<EOM

        Please make sure argument is a file! 
{$_SERVER['argv'][1]} is not a file.


EOM;
    die(
$message);
}


// -----------------------------
// IMPORT

//decide for tablename
$tablename substr$_SERVER['argv'][1], (strrpos($_SERVER['argv'][1], DIRECTORY_SEPARATOR) + ) );
$tablename str_ireplace('.txt'''$tablename);
$tablename str_ireplace('.dbf'''$tablename);
$tablename str_ireplace(' ''_'$tablename);
$tablename strtolower($tablename);
$tablename preg_replace('#^[^a-z0-9]$#'''$tablename);


//create table with fieldnames from line 1 of importfile
$fh fopen($_SERVER['argv'][1], 'r');
$stop_reading false;
while ( 
$stop_reading === false ) {
    
$firstline fgets($fh10000);
    
$stop_reading true//stop after first line
}

//sometimes the file is the dbf-file instead the tab-file, do mention this mistake!
if ( !preg_match("/\n/"$firstline) ) {
    die(
"\n\n!! Possible Mistake detected: use the tab-delimited files and not bdf-files directly - your file was " $_SERVER['argv'][1] . ".\n\n");
}


$firstline str_replace('#'''$firstline);  //remove prefixed comment char
$firstline str_replace("\n"''$firstline); //remove suffixed newline
$firstline strtolower($firstline);
$fieldnames_arr explode("\t"$firstline);

$sql_fields_create_part '';
$sql_insert_fields_part '';
foreach (
$fieldnames_arr as $fieldname) {
    
$sql_fields_create_part .= '`' $fieldname '` TEXT, ';
    
$sql_insert_fields_part .= '`' $fieldname '`, ';
}
$sql_fields_create_part substr($sql_fields_create_part0, -2); //cut off trailing ', '
$sql_insert_fields_part substr($sql_insert_fields_part0, -2); //cut off trailing ', '

$create_table_sql 'DROP TABLE IF EXISTS ' $tablename '; CREATE TABLE ' $tablename ' (' $sql_fields_create_part ') ENGINE = MYISAM ;';
echo 
$create_table_sql."\n\n\n";


//import records, continue reading the file
$rec_counter 0;
while ( !
feof($fh) ) {
    
$line fgets($fh);
    
$line str_replace("\n"''$line);
    if ( 
strlen($line)==) {
        continue;
    }
    
$field_values_arr explode("\t"$line);
    
$sql_insert_fields_value_part '';
    foreach(
$field_values_arr as $field_value) {
        
$sql_insert_fields_value_part .= '\'' mysql_escape_string($field_value) . '\', ';;
    }
    
$sql_insert_fields_value_part substr($sql_insert_fields_value_part0, -2); //cut off trailing ', '
    
$insert_sql 'INSERT INTO ' $tablename ' ( ' $sql_insert_fields_part ') VALUES (' $sql_insert_fields_value_part ');';
    echo 
$insert_sql "\n";
    
$rec_counter++;
}
fclose($fh);


// -----------------------------