Samstag, 11. Oktober 2014

PHP CSV detect delimiter

/**
 * @param string $csvFile Path to CSV file
 * @return string
 */
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);
}

Keine Kommentare:

Kommentar veröffentlichen