First of all, this is a very bad structure of doing things!! This will only work if:
- All the field values only have one space between words.
AND
- All the spaces between the fields are AT LEAST two spaces. Otherwise there is no way to tell the computer when one field ends and the other starts.
To split the fields whenever there are 2 or more spaces, use the following code:
foreach ($array as $line) {
// split
$fields = preg_split ("/\\s{2,}/", $line);
// insert
mysql_query("INSERT INTO table (field1, field2, field3) VALUES ('$fields[0]', '$fields[1]', '$fields[2]')");
}
I also took the comma out as it seems that there might be commas in some of the fields. The code above will now split whenever there is more than one whitespace character.
So this will work:
field 1 field 2 field 3
But this will NOT work:
field 1 field 2 field 3
As there is more than 1 space between the field values... so the above example would return 6 fields instead of the 3 you would want.
If there are more than 2 spaces in some fields, then you can increase the number in the code. However, as you increase the number to let more spaces in the field values, it also increases the number of spaces needed to separate a field. So if you did it up to 3, this would no longer work:
field 1 field 2 field 3
As there are 2 spaces between field 1 and 2, but also 2 spaces between "field" and "2" in field 2.
Yay for non comma separated files...
-Percy