2

I have the following code, that I use to read a csv file with CRLF as lines endings

if (($fp = fopen($path, "r")) !== FALSE) {
            while (($record = fgetcsv($fp, 1000, "\r\n")) !== FALSE) {
                if ($row == 0) {
                    $record[0] = $batchHeader;
                }
                $newCsvData[] = $record;
                $row++;
            }
        }

When I upload the csv file I get the following error: fgetcsv(): delimiter must be a single character

Here is a sample or my csv:

enter image description here

Thanks.

oussama kamal
  • 1,027
  • 2
  • 20
  • 44
  • `"\r\n"`...you have two characters there... – Hackerman Nov 23 '17 at 18:13
  • Try use [PHP_EOL](https://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol). (I haven't tested if this will work for fgetcsv) – RToyo Nov 23 '17 at 18:15
  • As mentioned, you can only use 1 character and you're trying to use both a carriage return and line feed. Just apply the `\r` before the `\n` and use `\n` as the delimiter. – cchoe1 Nov 23 '17 at 18:16
  • @RToyota in terms of the .csv, a PHP_EOL will not create a new line so normally, it's not used as a delimiter. `\n` in a .csv (or any text file) will create a new line which gives .csv files slightly better readability. As a result, using a PHP_EOL won't do much good (it will also be visible and no new lines will be created). Although OP is kinda missing the point of .csv files and using a `\n` as a delimiter since it's automatically handled if you use commas as a delimiter and simply iterate over every row. – cchoe1 Nov 23 '17 at 18:19

2 Answers2

5

I'm guessing it reads "\r\n" as your delimiter. Have you tried fgetcsv($fp, 1000, "|") ?

It should auto-detect line endings.

PHP reference

2

The parameter in question is the delimiter (field separator), not the row separator. In your case, |should be your delimiter. The function will handle line endings itself.

Take a read for more information at http://php.net/manual/en/function.fgetcsv.php

SEoF
  • 1,092
  • 14
  • 26