Skip to content

Commit 6f706e6

Browse files
committed
Added detect delimiter
1 parent acadb03 commit 6f706e6

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ The following options are available to suit your needs:
8484
These options could be passed to the `open` and `save` methods, be set using the `options` method, or be set as the
8585
global default using the static `defaults` method.
8686

87+
The delimiter can be detected for a file by using the `detectDelimiter` method like this:
88+
89+
```
90+
CsvCollection::detectDelimiter($path);
91+
```
92+
8793
#### Header
8894

8995
When using a header, lines will contain an associated array. Otherwise, lines will contain an indexed array.

src/CsvCollection.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,24 @@ public function push(string $file, array $line, array $options = []): self
156156
return $this->open($file, $options);
157157
}
158158

159+
/**
160+
* @param string $file Path to the CSV file
161+
* @return string Delimiter
162+
*/
163+
public static function detectDelimiter(string $file): string
164+
{
165+
$delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];
166+
167+
$handle = fopen($file, "r");
168+
$firstLine = fgets($handle);
169+
fclose($handle);
170+
foreach ($delimiters as $delimiter => &$count) {
171+
$count = count(str_getcsv($firstLine, $delimiter));
172+
}
173+
174+
return array_search(max($delimiters), $delimiters, true);
175+
}
176+
159177
/**
160178
* Set the collection's options.
161179
*

0 commit comments

Comments
 (0)