Detect the line ending character of a csv file

Viewed 4405

I need to detect what kind of line endings are in a csv file:

  • \n (UNIX default)
  • \r (Mac Excel)
  • \r\n (Windows)
  • or anything else

To get the delimeter, encosure & escape character, I used SplFileObject::getCsvControl - would be to great to have something like that for the line ending char.

Opening the file

3 Answers

I've used the @rickdenhaan solution and I've found a problem with arsort() and PHP Version.

if eol is "\r\n" the $eols array will be:

array("\r\n" => 1, "\r" => 1, "\n" => 1);

(because in addition to 1 "\r\n" is also found 1 "\r" and 1 "\n")

and with PHP 7, after arsort($eols), the keys order is the same:

array("\r\n" => 1, "\r" => 1, "\n" => 1);

and after the "$eol = key($eols);" $eol will be "\r\n"

But with PHP 5.6, after arsort($eols), the keys order is:

array("\n" => 1, "\r" => 1, "\r\n" => 1);

and after the "$eol = key($eols);" $eol will be "\n"

I've solved with this check after "$eol = key($eols);":

if (($eols["\r\n"] == $eols["\r"]) AND ($eols["\r\n"] == $eols["\n"])) {
    $line_separator = "\r\n";
}
Related