It seems that the delimiter of csv file edited and saved by OpenOffice Excel is ";" while microsoft office excel is ",", how should i write a program to parse the csv file no matter which delimiter it uses?
Asked
Active
Viewed 4,124 times
3 Answers
2
I'm using this function in one of my apps to determine which separator is used:
function get_separator( $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;
}
It basically checks which separator occurs at most and returns it. It works without problems for about two years now

Xaver
- 11,144
- 13
- 56
- 91
1
Use SplFileObject::getCsvControl method. Example usage:
<?php
$csvFileObject = new SplFileObject($_FILES["csv"]["tmp_name"]);
list($delimiter, $enclosure) = $csvFileObject->getCsvControl();
$lines = fopen($_FILES["csv"]["tmp_name"], 'r');
if($lines) {
while (($line = fgetcsv($lines, 4096, $delimiter, $enclosure)) !== false) {
//do something
}
}
Reference: http://php.net/manual/en/splfileobject.getcsvcontrol.php

stz184
- 363
- 3
- 12
-
1This method does not work properly in 5.5 (maybe in older versions too). – Kirill Titov Jan 10 '15 at 11:53
0
fgetcsv()
allows you to specify the delimiter as the third argument.
As for automatically detecting, there are some interesting answers for this question.