如何找出csv文件字段是否以制表符分隔或以逗号分隔

Sow*_*nil 12 php

如何找出csv文件字段是否以制表符分隔或以逗号分隔.我需要php验证.任何人都可以帮忙.提前致谢.

Jay*_*att 25

现在回答这个问题为时已晚,但希望能帮到某个人.

这是一个简单的函数,它将返回文件的分隔符.

function getFileDelimiter($file, $checkLines = 2){
        $file = new SplFileObject($file);
        $delimiters = array(
          ',',
          '\t',
          ';',
          '|',
          ':'
        );
        $results = array();
        $i = 0;
         while($file->valid() && $i <= $checkLines){
            $line = $file->fgets();
            foreach ($delimiters as $delimiter){
                $regExp = '/['.$delimiter.']/';
                $fields = preg_split($regExp, $line);
                if(count($fields) > 1){
                    if(!empty($results[$delimiter])){
                        $results[$delimiter]++;
                    } else {
                        $results[$delimiter] = 1;
                    }   
                }
            }
           $i++;
        }
        $results = array_keys($results, max($results));
        return $results[0];
    }
Run Code Online (Sandbox Code Playgroud)

使用此功能如下所示:

$delimiter = getFileDelimiter('abc.csv'); //Check 2 lines to determine the delimiter
$delimiter = getFileDelimiter('abc.csv', 5); //Check 5 lines to determine the delimiter
Run Code Online (Sandbox Code Playgroud)

PS我使用了preg_split()而不是explode(),因为explode('\ t',$ value)不会给出正确的结果.

更新:感谢@RichardEB指出代码中的错误.我现在更新了这个.


Dre*_*ion 11

这就是我的工作.

  1. 解析CSV文件的前5行
  2. 计算每行中分隔符的数量[逗号,制表符,分号和冒号]
  3. 比较每行中的分隔符数.如果您具有格式正确的CSV,则其中一个分隔符计数将在每行中匹配.

这不会在100%的时间内起作用,但它是一个不错的起点.至少,它会减少可能的分隔符数量(使用户更容易选择正确的分隔符).

/* Rearrange this array to change the search priority of delimiters */
$delimiters = array('tab'       => "\t",
                'comma'     => ",",
                'semicolon' => ";"
                );

$handle = file( $file );    # Grabs the CSV file, loads into array

$line = array();            # Stores the count of delimiters in each row

$valid_delimiter = array(); # Stores Valid Delimiters

# Count the number of Delimiters in Each Row
for ( $i = 1; $i < 6; $i++ ){
foreach ( $delimiters as $key => $value ){
    $line[$key][$i] = count( explode( $value, $handle[$i] ) ) - 1;
}
}


# Compare the Count of Delimiters in Each line
foreach ( $line as $delimiter => $count ){

# Check that the first two values are not 0
if ( $count[1] > 0 and $count[2] > 0 ){
    $match = true;

    $prev_value = '';
    foreach ( $count as $value ){

        if ( $prev_value != '' )
            $match = ( $prev_value == $value and $match == true ) ? true : false;

        $prev_value = $value;
    }

} else { 
    $match = false;
}

if ( $match == true )    $valid_delimiter[] = $delimiter;

}//foreach

# Set Default delimiter to comma
$delimiter = ( $valid_delimiter[0] != '' ) ? $valid_delimiter[0] : "comma";


/*  !!!! This is good enough for my needs since I have the priority set to "tab"
!!!! but you will want to have to user select from the delimiters in $valid_delimiter
!!!! if multiple dilimiter counts match
*/

# The Delimiter for the CSV
echo $delimiters[$delimiter]; 
Run Code Online (Sandbox Code Playgroud)


rel*_*let 8

没有100%可靠的方法来确定这一点.你能做的是

  • 如果您有一种方法来验证您阅读的字段,请尝试使用任一分隔符读取一些字段并根据您的方法进行验证.如果它坏了,请使用另一个.
  • 计算文件中标签或逗号的出现次数.通常一个明显高于另一个
  • 最后但并非最不重要:询问用户,并允许他覆盖您的猜测.


小智 6

我只是计算 CSV 文件中不同分隔符的出现次数,最多的应该是正确的分隔符:

//The delimiters array to look through
$delimiters = array(
    'semicolon' => ";",
    'tab'       => "\t",
    'comma'     => ",",
);

//Load the csv file into a string
$csv = file_get_contents($file);
foreach ($delimiters as $key => $delim) {
    $res[$key] = substr_count($csv, $delim);
}

//reverse sort the values, so the [0] element has the most occured delimiter
arsort($res);

reset($res);
$first_key = key($res);

return $delimiters[$first_key]; 
Run Code Online (Sandbox Code Playgroud)


小智 5

在我的情况下,用户提供 csv 文件,然后将其输入到 SQL 数据库中。他们可能会将 Excel 电子表格另存为逗号或制表符分隔文件。将电子表格转换为 SQL 的程序需要自动识别字段是制表符分隔还是逗号分隔

许多 Excel csv 导出将字段标题作为第一行。标题测试不太可能包含逗号,除非作为分隔符。对于我的情况,我计算了第一行的逗号和制表符,并使用较大的数字来确定它是 csv 还是制表符