veli veli - 2 months ago 19
PHP Question

Reading from comma or tab delimited text file

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.

Answer

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

$someCondition = someConditionToDetermineTabOrComma();

$delimiter = $someCondition ? "," : "\t";

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

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

    $data = str_getcsv($line, $delimiter);

    doSomethingWithData($data);
}                              

fclose($fp);
Comments