Search code examples
phpdelimiterfgetcsv

PHP - fgetcsv - Delimiter being ignored?


I'm trying to output each line in a csv file, and it seems like the delimiter is being ignored... I'm sure my syntax is wrong somewhere, but can't seem to pinpoint it...

The CSV file looks like this:

ID,Code,Count
TM768889,02001,10
TM768889,02002,10
TM768889,02003,10
TM768889,02004,10
TM768889,02005,10

I'm trying to output:

   0 - ID,Code,Count
   1 - TM768889,02001,10
   2 - TM768889,02002,10
   3 - TM768889,02003,10
   4 - TM768889,02004,10
   5 - TM768889,02005,10

But instead, it's outputting this:

0 - ID
1 - Code
2 - Count TM768889
3 - 02001
4 - 10 TM768889
5 - 02002
6 - 10 TM768889
7 - 02003
8 - 10 TM768889
9 - 02004
10 - 10 TM768889
11 - 02005
12 - 10

Here's my code:

  $row = 0;
  if(($handle = fopen($_FILES["Filedata"]["tmp_name"], "r")) !== FALSE) {
              $string = '';
              while(($line = fgetcsv($handle,1000,",")) !== FALSE) {
                    $num = count($line);
                    $row++;
                    for($c=0; $c < $num; $c++) {
                              $string .= $c.' - '.$line[$c].'<br />';
            }
          }     
  fclose($handle);
  echo $string;
  }

Solution

  • Why bother with fgetcsv? You're just taking the line and spitting it back out, so it seems like you could just use fgets instead:

      $row = 0;
      if(($handle = fopen($_FILES["Filedata"]["tmp_name"], "r")) !== FALSE) {
                  $string = '';
                  while(($line = fgets($handle)) !== FALSE) {
                        $row++;
                        $string .= $row.' - '.$line.'<br />';
                }
              }     
      fclose($handle);
      echo $string;
      }
    

    Your problem is that you are printing out a full line for each value in the CSV file, rather than the line as a whole like you intend.