qsldcq
Last Updated: July 12, 2017
·
2.782K
· markus-perl
10620301 745710515470370 5763874756421604255 o

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);
}
Say Thanks
Respond