Last active
July 26, 2017 10:59
-
-
Save andreyserdjuk/ab4743053bd6173593ab to your computer and use it in GitHub Desktop.
determine csv delimiter php
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
<?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