tags:

views:

417

answers:

6

I need to read the data from a file that can be either comma or tab delimited. I now that there is a function getcsv but it accepts only one possible delimiter.

Any ideas how to handle this?

Thanks.

A: 

Read the whole file, or line by line and split it using split.

There you can include a regex with arbitrary delimiters. I have not PHP here to test a statement, but php.net -> search for split(). There you also have a comment relating to regex.

StampedeXV
But that method would eliminate the enclosure functionality of getcsv, likely defeating the purpose of all but the simplest of csv files.
dimo414
A: 

This article may be of use to you

Simon Scarfe
+1  A: 

Starting from PHP 5.3, you can use str_getcsv() to read individual lines using different delimiters.

$fp = fopen('mydata.csv', 'r');

while ( !feof($fp) )
{
    $line = fgets($fp, 2048);

    $someCondition = someConditionToDetermineTabOrComma();

    $delimiter = $someCondition ? "," : "\t";
    $data = str_getcsv($line, $delimiter);

    doSomethingWithData($data);
}                              

fclose($fp);
MathieuK
I came to similar solution. I read the file and search for tab in it; if not found I assume that the delimiter is comma. Then use getscv as version of php is 5.2. Although I see some flaws in this, I can't think of anything better.
A: 

It always bugs me when people make suggestions like this, but I'd definitely suggest seeing if there's some way to ensure a given file is either comma or tab delimited, not both. This will make your job much, much easier.

If this is not possible, I would suggest doing a preg_replace on one of them (probably tab) assuming that you can be sure that one will never be inside an enclosure.

dimo414
A: 

you can try explode ( string $delimiter , string $string [, int $limit ] )

In comma separated file there can be a comma inside quotes which is not considered as a delimiter. That's why I want to use getscv, as it handles this properly.
A: 

You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,

 while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    ...
 }
ZZ Coder
Yes, but it can be also a csv file. The problem is how to tell for sure if it is csv or tab delemited.