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.
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.
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.
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);
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.
You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
...
}