Reputation: 7777
I'm using fgetcsv
to read csv files in my application. Problem is that I don't know if my users will use ,
, |
, or ;
as delimiters. If I tell fgetcsv
nothing it will only accept ,
but if I tell it to use a specific delimiter it will only accept that.
What I'm doing now is:
while (($row = fgetcsv($fileHandle, 4096)) !== false) {
What I want is something like this:
while (($row = fgetcsv($fileHandle, 4096, array(',', ';', '|'))) !== false) {
Is that possible in some easy way? It seems really weird that you would have to limit your delimiter to one specific character, since CSV is not standardized.
Upvotes: 6
Views: 1232
Reputation: 7777
Just to provide a simple answer for anyone else struggling with this. The solution I settled on was to replace all the delimiters to a specific character. Like this:
private function replaceDelimiters($file)
{
// Delimiters to be replaced: pipe, comma, semicolon, caret, tabs
$delimiters = array('|', ';', '^', "\t");
$delimiter = ',';
$str = file_get_contents($file);
$str = str_replace($delimiters, $delimiter, $str);
file_put_contents($file, $str);
}
Note that this will replace all given characters to a ','. So this will only be a good option if you know that those characters will only be used as delimiters, not content. (as in my case)
Also did a blog post about it.
Upvotes: 0
Reputation: 1418
Use the league/csv package, this has a detection feature and more features that make it worth using it over fgetcsv.
Upvotes: 1
Reputation: 157967
You cannot reliably determine the delimiter of a csv file if you don't know it. Take this simple example:
foo;bar,hello;world
What is the delimiter? ,
or ;
? If you would pass an array array(',',';')
what data are you expecting fgetcsv()
will return?
If you don't know the delimiter you need to ask the user for it.
Upvotes: 6