When I explode the lines of a .csv
file with a tab as delimiter, like such:
// $handle = some TSV file
while (($line = fgets($handle)) !== false) {
$fields = explode("\t",$line);
}
If the last column of the row is empty (or maybe even if it isn't), for some reason the last element in $fields
will contain a newline (\n
). This is causing problems and I can't quite figure out why it does this, and if it is normal, how to compensate for it.
The csv file is typical like so:
col1\tcol2\tcol3\n
col1\tcol2\tcol3\n
...
*The \t and \n are real tabs and new lines in the file.
So in this instance, if col3 was empty, my issue would persist. It might even do so if it isn't empty.
NOTE: The issue is that I am inserting each of the columns into a MySQL database and the last column has a newline in it. When I export this database back to CSV, it breaks the layout of the file.
So now my question(s) are:
Is this normal behavior?
If so, what can I do about it if I can't have a newline in the last $field?
1. Since you use
fgets()
, yes this is the expected behaviour, since you grab the full line, which includes the new line character at the end.2. You can just use
fgetcsv()
and specify the delimiter as tab, e.g.Just to add an alternative solution here:
You can get your file into an array with
file()
and ignore the new line characters at the end with a flag, so you do something similar as whatfgets()
does. And thenexplode()
each line by a tab, e.g.