Skip to content

Instantly share code, notes, and snippets.

@andreyserdjuk
Last active July 26, 2017 10:59
Show Gist options
  • Save andreyserdjuk/ab4743053bd6173593ab to your computer and use it in GitHub Desktop.
Save andreyserdjuk/ab4743053bd6173593ab to your computer and use it in GitHub Desktop.
determine csv delimiter php
<?php
/**
* Determine csv delimiter
*
* @param resource $fileHandle - handle of csv file
* @return string - correct delimiter of csv file
*/
function determineCsvDelimiter($fileHandle)
{
$delimiters = array(';', "\t", ",", "|", ":");
foreach ($delimiters as $delimiter) {
while (($csvRow = fgetcsv($fileHandle, 500, $delimiter)) !== FALSE) {
try {
$countColumns = count($csvRow);
if ($countColumns > 1) {
// may be it is delimiter but its count must be equal with next rows
if (isset($cacheCountColumns)) {
if ($cacheCountColumns != $countColumns) {
throw new Exception("Delimiters count is not equal");
}
} else {
$cacheCountColumns = $countColumns;
}
} else {
throw new Exception("Delimiter is not correct");
}
} catch (Exception $e) {
// different delimiters count in rows
// try to find other delimiter
break;
}
// exception didn't thrown, so delimiter found
break 2;
}
}
rewind($fileHandle);
return $delimiter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment