PHP + CSV -> Autodetect Delimiter
This method catches the first line of a CSV file and tries to parse the line with different delimiters. The delimiter who finds the most rows will be returned.
* @param string $csvFile Path to the CSV file
* @return string Delimiter
*/
public function detectDelimiter($csvFile)
{
$delimiters = array(
';' => 0,
',' => 0,
"\t" => 0,
"|" => 0
);
$handle = fopen($csvFile, "r");
$firstLine = fgets($handle);
fclose($handle);
foreach ($delimiters as $delimiter => &$count) {
$count = count(str_getcsv($firstLine, $delimiter));
}
return array_search(max($delimiters), $delimiters);
}
Written by Markus Perl
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#