Created
October 2, 2018 14:08
-
-
Save cuonghuynh/8f87e15355f1c42bd1236cf5cb9f09c3 to your computer and use it in GitHub Desktop.
Detect delimiter of csv file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Class CsvHelpers | |
* @package App\Services\Common | |
*/ | |
class CsvHelpers | |
{ | |
/** | |
* @param $file | |
* @return string | |
*/ | |
public static function detectDelimiter($file) | |
{ | |
$delimiters = [ | |
';' => 0, | |
',' => 0, | |
'\t' => 0, | |
'|' => 0 | |
]; | |
$handle = fopen($file, 'rb'); | |
$firstLine = fgets($handle); | |
fclose($handle); | |
foreach ($delimiters as $delimiter => &$count) { | |
$count = \count(str_getcsv($firstLine, $delimiter)); | |
} | |
return array_search(max($delimiters), $delimiters, true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment