在 PHP 中使用逗号或分号文件打开 CSV

Gui*_*ire 2 php csv

我想用 php 打开一个 CSV 文件,但输入可以是逗号或分号,我该怎么做

我用逗号打开文件

if (($handle = fopen($filePath, 'r')) !== false) {
    // get the first row, which contains the column-titles (if necessary)
    $header = fgetcsv($handle);
      while (($data = fgetcsv($handle)) !== false) {
        var_dump($data);
      }
}
Run Code Online (Sandbox Code Playgroud)

我的文件可以

   Test;option;money
   1;a;1,3
   2;"G;a";1,965,0
Run Code Online (Sandbox Code Playgroud)

或者

   Test,option,money
   1,a,"1,3"
   2,"G;a",1,"965,0"
Run Code Online (Sandbox Code Playgroud)

我如何测试分隔符以使用 fgetcsv ?

act*_*ctc 6

也许您可以在这篇 StackOverflow 文章中找到答案。它提出了一种分隔符检测方法的实现。实现是:

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($filePath); // actual path of the file, ex: '../example.csv'

if (($handle = fopen($filePath, 'r')) !== false) {
    // get the first row, which contains the column-titles (if necessary)
    $header = fgetcsv($handle, 0, $delimiter);
      while (($data = fgetcsv($handle)) !== false) {
        var_dump($data);
      }
}
Run Code Online (Sandbox Code Playgroud)