Parse Tab Delimited txt file into MySql

Discussion in 'PHP' started by mbk, Feb 17, 2010.

  1. #1
    I have a Tab delimited txt file that I need to import into a mysql database, however I am having an issue in that I dont think there is an end of line character within the file.

    The code below is something i have picked up via google and made a couple of amends to, can someone please look at this and see if they can see anything obviously wrong with it?

    The txt file itself is in the same directory at the mintue as the php file and when opened with either open office word or spreadsheet doesnt contain any | between fields, just tabs.

    I would include a link to the txt file however it is 75MB.

    Thanks
    <?php
    
    // Set Mysql Variables
    //$host = 'localhost';
    //$user = 'root';
    //$pass = 'ASsC9XlI';
    //$db = 'testdb';
    $table = 'on_market_dump';
    
    $username = "user";
    $pass = 'mypass';
    $db = mysql_connect("localhost", $username, $pass);
    mysql_select_db("testdb",$db); 
    
    //mysql_connect($host,$user,$pass) or die(mysql_error());
    $empty_table = "TRUNCATE TABLE '$table'";
    mysql_query($empty_table) or die (mysql_error());
    
    $file = "on_market.export_urls_rich.txt";
    $fp = fopen($file, "r");
    $data = fread($fp, filesize($file));
    fclose($fp);
    
    //$output = str_replace("\t|\t", "|", $data);
    
    $output = explode("\n", $output);
    
    //mysql_connect($host,$user,$pass) or die(mysql_error());
    
    foreach($output as $var) {
    $tmp = explode("\t", $var);
    $productid = $tmp[0];
    $prodid = $tmp[1];
    $quality = $tmp[2];
    $url_spec = $tmp[3];
    $supplier_id = $tmp[4];
    $highres = $tmp[5];
    $lowres = $tmp[6];
    $thumbnail = $tmp[7];
    $uncatid = $tmp[8];
    $catid = $tmp[9];
    $manu_pn = $tmp[10];
    $ean_upcs = $tmp[11];
    $modelname = $tmp[12];
    $onmarket = $tmp[15];
    $countries = $tmp[16];
    $updated = $tmp[17];
    
    
    $sql = "INSERT INTO $table SET productid='$productid', prodid='$prodid', quality='$quality'";
    mysql_query($sql)or die (mysql_error());
    
    }
    echo "Done!";
    
    
    ?>
    PHP:
     
    mbk, Feb 17, 2010 IP