how to find out if csv file fields are tab delimited or comma delimited

后端 未结 15 998
[愿得一人]
[愿得一人] 2020-12-01 09:46

how to find out if csv file fields are tab delimited or comma delimited. I need php validation for this. Can anyone plz help. Thanks in advance.

15条回答
  •  抹茶落季
    2020-12-01 10:35

    Thanks for all your inputs, I made mine using your tricks : preg_split, fgetcsv, loop, etc.

    But I implemented something that was surprisingly not here, the use of fgets instead of reading the whole file, way better if the file is heavy!

    Here's the code :

    ini_set("auto_detect_line_endings", true);
    function guessCsvDelimiter($filePath, $limitLines = 5) {
        if (!is_readable($filePath) || !is_file($filePath)) {
            return false;
        }
    
        $delimiters = array(
            'tab'       => "\t",
            'comma'     => ",",
            'semicolon' => ";"
        );
    
        $fp = fopen($filePath, 'r', false);
        $lineResults = array(
            'tab'       => array(),
            'comma'     => array(),
            'semicolon' => array()
        );
    
        $lineIndex = 0;
        while (!feof($fp)) {
            $line = fgets($fp);
    
            foreach ($delimiters as $key=>$delimiter) {
                $lineResults[$key][$lineIndex] = count (fgetcsv($fp, 1024, $delimiter)) - 1;
            }
    
            $lineIndex++;
            if ($lineIndex > $limitLines) break;
        }
        fclose($fp);
    
        // Calculating average
        foreach ($lineResults as $key=>$entry) {
            $lineResults[$key] = array_sum($entry)/count($entry);
        }
    
        arsort($lineResults);
        reset($lineResults);
        return ($lineResults[0] !== $lineResults[1]) ? $delimiters[key($lineResults)] : $delimiters['comma'];
    }
    

提交回复
热议问题