veli veli - 1 year ago 111
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?


Answer Source

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);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download