I have a problem with reading a tab delimited file.
The structure on my file is:
Field 1 Field 2 Field 3
Element11 Element12 Element13
Elemen
fgetcsv():
$result = array();
$fp = fopen('/path/to/file','r');
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) $result[] = $line;
fclose($fp);
print_r($result);
If you want to skip the header row, just call fgets()
once before you enter the loop. Or if you want the array to be associative as depicted above:
$result = array();
$fp = fopen('/path/to/file','r');
$headers = fgetcsv($fp, 0, "\t");
$row = 0;
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) {
for ($col = 0; isset($line[$col]); $col++) {
$result[$row][$header[$col]] = $line[$col];
}
$row++;
}
fclose($fp);
print_r($result);
To also get the headers as array keys you need
$result = array();
$fp = fopen('/path/to/file','r');
if (($headers = fgetcsv($fp, 0, "\t")) !== FALSE)
if ($headers)
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE)
if ($line)
if (sizeof($line)==sizeof($headers))
$result[] = array_combine($headers,$line);
fclose($fp);
print_r($result);