Question

How'd I go about reading a tab delimited .txt file and then coding it so it puts each column of data(that is seperated with a tab) into a php variable.

for example....

505050 somedata moredata

and then, writing these variables to

$id $somedata $moredata

I read into fgetcsv and making an array although it seemed to make the whole line an array i need to split it into variables so that i can write it to individual columns in the MySQL database,

Can anyone give me any pointers?

Thanks so much...

Was it helpful?

Solution

A combination of fgetcsv() and list() will be the most efficient way to split this into named variables:

list($id, $somedata, $moredata) = fgetcsv($fp, 0, "\t");

However, you do not need to have them as named variables in order to insert them in MySQL, you can just use the raw array returned by fgetcsv():

$row = fgetcsv($fp, 0, "\t");

$query = "
  INSERT INTO `tablename`
    (`id`, `somedata`, `moredata`)
  VALUES
    ('{$row[0]}', '{$row[1]}', '{$row[2]}')
";

Don't forget to escape the data before using it in a query ;-)

OTHER TIPS

explode() will split a string. Try this:

list($id, $somedata, $moredata) = explode("\t", $string);

Where $string is the string you want to split. For more info about explode() and list(), just look up on php.net.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top