views:

177

answers:

2

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;
  }
+1  A: 

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.

Billy ONeal
Thanks! I appreciate the pointer...
TwixxyKit
+1  A: 

Firstly your code does not print what you pasted. The counter does not match the $c variable.

This is what I get:

0 - ID
1 - Code
2 - Count
0 - TM768889
1 - 02001
2 - 10
0 - TM768889
1 - 02002
2 - 10
0 - TM768889
1 - 02003
2 - 10
0 - TM768889
1 - 02004
2 - 10
0 - TM768889
1 - 02005
2 - 10

If your data file is not huge then I advise you to load the file into an array using the file() function. Then you can loop thru the array and output the value which is simply the line.

$lines=file($_FILES["Filedata"]["tmp_name"]);
foreach($lines as $line) print($line.'<br/>');

If you then need to parse the line then just use the explode() function to get at each value.

zaf