PHP fgetcsv() delimiter
Solution 1
1. The enclosure
parameter is the character the encapsulates the data for a specific field, or "index". By default, the parameter is a "
, which means that you can "enclose" strings in "
characters.
Example:
1,2,"this is three",4
2. Per a comment, you're calling fgetcsv($handle, 10000, ',')
. It's possible, maybe, that the line(s) you're reading are longer than 10000 characters. Try changing the length to 0
, which will be "no limit" and see if that helps. Another solution would be to try wrapping the column's value in double-quotes.
Solution 2
Enclosure is the character enclosing the field. It is an extra delimiter, of a sort.
For example hello,world
has a comma as field delimiter, and has no text delimiter, while "hello","world"
has a quote sign as text delimiter. Some systems employ delimited and undelimited values to indicate text and numeric fields, respectively (I believe Microsoft Excel does). This allows a field to contain the field delimiter in its value:
"Hello,world","Second Field","Third, and last, field".
Some other systems only enclose values containing the field delimiter, or values containing whitespace, which means that on those systems an undelimited value is not necessarily numeric.
If you have a "trivial" case - undelimited values, without escaped field-delimiters inside values (i.e., no 'A,firstpartB\,secondpartB,C' stuff) - you might skip CSV conversion altogether and run
$line = fgets($file, MAX_EXPECTED_LINE_LEN);
// This splits ' A, B, C ' into 'A', ' B' and ' C' (note spaces)
$row = explode(',', trim($line)); // other delimiters can be used
or
// Consider " , ", "," and ", " as the same delimiter
// i.e. ' Alpha , Beta , Gamma ' gets split into 'Alpha', 'Beta' and 'Gamma'
$row = preg_split('#\\s*,\\s*#', trim($line));
I cannot seem to reproduce the problem you are experiencing; could it be related to a different encoding of line endings (i.e., CRLF instead of LF)?
In a pinch, you can divide fgetcsv
in the two components fgets
and str_getcsv()
, manipulating the line between the calls (with trim
, or if the worse comes to the worst, by appending the missing comma).
Mohammad Saberi
Updated on June 27, 2022Comments
-
Mohammad Saberi almost 2 years
Regarding to
fgetcsv()
documentation, there are some parameteres insidefgetcsv()
function: Handle, length, delimiter, enclosure, and escape.Now, I have 2 questions:
- What does enclosure do exactly?
- I have a csv file with 5 columns per line. Imagine it something like this: 1,2,3,4,5
So indexes are from 0 to 4. But whenever I want to get date from index 4, an empty value returns. Unless I put a comma after it (by filling an extra column after it that makes the contents like this: 1,2,3,4,5,6 ). How can I solve this issue ? It seems that there is some problem because of missing comma after the last item in each row of csv file!