Last Updated: July 26, 2024
·
13.03K
· markus-perl

PHP + CSV -> Autodetect Delimiter

This method catches the first line of a CSV file and tries to parse the line with different delimiters. The delimiter who finds the most rows will be returned.

* @param string $csvFile Path to the CSV file
* @return string Delimiter
*/
public function detectDelimiter($csvFile)
{
    $delimiters = array(
        ';' => 0,
        ',' => 0,
        "\t" => 0,
        "|" => 0
    );

    $handle = fopen($csvFile, "r");
    $firstLine = fgets($handle);
    fclose($handle); 
    foreach ($delimiters as $delimiter => &$count) {
        $count = count(str_getcsv($firstLine, $delimiter));
    }

    return array_search(max($delimiters), $delimiters);
}