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.
The Comma Delimited file is a file in which values are separated by commas. The . csv format can be viewed in Microsoft Excel. The Tab Delimited file is a file in which values are separated by tabs.
A CSV (Comma Separated Values) or Tab-delimited Text (or Tab Separated Values) file is a text file in which one can identify rows and columns. Rows are represented by the lines in the file and the columns are created by separating the values on each line by a specific character, like a comma or a tab.
A tab-delimited file contains rows of data. Each row of data contains one or more pieces of data. Each piece of data is called a field. Tab-delimited files to be read by the Data Integrator must contain the same number of fields in every row, although not every field necessarily needs a value.
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);
You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With