Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from comma or tab delimited text file

Tags:

php

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.

like image 242
veli Avatar asked Sep 03 '09 08:09

veli


People also ask

What is the difference between tab-delimited and comma delimited?

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.

What is a CSV or tab-delimited text file?

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.

What is a tab-delimited text file?

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.


2 Answers

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); 
like image 95
NSSec Avatar answered Oct 18 '22 17:10

NSSec


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

 while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {     ...  } 
like image 33
ZZ Coder Avatar answered Oct 18 '22 18:10

ZZ Coder