Skip to content

Instantly share code, notes, and snippets.

@cuonghuynh
Created October 2, 2018 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuonghuynh/8f87e15355f1c42bd1236cf5cb9f09c3 to your computer and use it in GitHub Desktop.
Save cuonghuynh/8f87e15355f1c42bd1236cf5cb9f09c3 to your computer and use it in GitHub Desktop.
Detect delimiter of csv file
/**
* 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