Hi.
I need to input data to mssql table from tab delimited file. Because the file has more than 4000 entries using a normal foreach loop obviously doesn't work. So I decided to try sql's BULK INSERT.
It kind of works but gives some errors:
the table has 51 fields, most of entries in the file also have 51 fields, but there is around a 1000 rows that have only 49 or 50 fields. The missing fields are ALWAYS at the end of the row.
When using BULK INSERT I have to upload complete file, so what I decided to do is:
read the file into array
count amount of fields in each row
if it equals 51 asign that row to variable
else
get the number of the last index of row array
run a loop where to the array I will insert additional index (\t) until number of indexes is equal to 51
asign the row to the same variable (.=)
create new file from the variable
fire up bulk insert.
Where I'm stuck is the adding of another index. Below is the code, any idea how to do it
<?php
$counter = 0;
$lines = file("db_import/test.TXT"); //read file content to array
$counter=1;
$numer =0;
foreach ($lines as $line) {
$cell = explode ("\t", $line);
$count = count($cell);
// if number of indexes in row is equal to 51
// assign the array to variable
if ($count == 51){
$testContent .= $lines;
}
// SO FAR WORKS GOOD WRITING THE DATA TO FILE
else {
// if not
end($cell); //go to last index
$lastIndex = key($cell); // assign las index number to variable
$tab = '\t'; //define tab
$tabno = 0;
while ($count < 51){ //until number of indexes equals 51 do
array_push($line, "\t"); //puch into array delimeter \t
$tabno++;
$count++;
}
$testContent .= $lines; //assign to variable and below writ to file
}
}
////////// create file
$testFile = "test2.txt";
$dir = "db_import/";
$testFileHandle = fopen($dir . $testFile, 'w') or die("Unable to create export file " . $testFile . "!");
fwrite($testFileHandle, $testContent);
fclose($testFileHandle);
?>