Answer the question
In order to leave comments, you need to log in
How to automatically detect CSV delimiter and encoding?
Please share examples of how you can automatically determine the delimiter and file encoding. The file is read with the "fgetcsv" function.
Found this method:
private function detectSeparator($csvstring, $fallback = ';'){
$seps = array(';',',','|',"\t");
$max = 0;
$separator = false;
foreach($seps as $sep){
$count = substr_count($csvstring, $sep);
if($count > $max){
$separator = $sep;
$max = $count;
}
}
if($separator) return $separator;
return $fallback;
}
Answer the question
In order to leave comments, you need to log in
Found on the site
function getSplitChar($str) {
$s = preg_replace('/".+"/isU', '*', $str);
$a = [',',';','|']; //список разделителей
$r;
$i = -1;
foreach($a as $c) {
if(($n = sizeof(explode($c, $s))) > $i) {
$i = $n;
$r = $c;
}
}
return $r;
}
//открываем файл
$handle = fopen("test.csv", "r");
$header = fgets($handle);
$char = getSplitChar($header);
//переходим назад к первой строке
fseek($header, 0);
while (($data = fgetcsv($handle, 1000, $char)) !== FALSE) {
$num = count($data);
echo "
$num полей в строке $row:
\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "
\n";
}
}
fclose($handle);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question