3

Is there a way to use fgetcsv to open on a particular row?

I have a really big csv and would like to run around 100 lines at a time via ajax. I can easily stop the while loop, but how would I open on a particular line? Or is this impossible?

Somk
  • 11,869
  • 32
  • 97
  • 143

2 Answers2

11

There's no simple way to start reading at row 100, but what you can do is read/set the position in the file like this:

$k = <previous position>;
fseek($file, $k);
while(...) {
   fgetcsv(...);
   ...
}
$k = ftell($file);   //new position

Now it's just a matter of preserving this position between page calls.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • Cheaper to just use fgets() for the skipping part and save the overhead of CSV parsing, since that data's just being thrown away. – Marc B Aug 23 '11 at 14:16
  • Cheaper than what? I was thinking of skipping it with `fseek()` without reading at all. `fgets()` will not work, since CSV file can include multi-line values, which `fgetcsv()` understands correctly, but `fgets()` would not. – Aleks G Aug 23 '11 at 14:34
  • Hmm. true enough. I really should remember to wake up first before working on an answer... – Marc B Aug 23 '11 at 14:36
  • @AleksG can you give a complete example, we don't need to use fopen here? – tarek fellah Jan 18 '17 at 10:36
0

The currently accepted answer doesn't seem to answer the actual the question. The posted question is how to open at a particular row. The answer above is great way to save a spot and come back to it, but doesn't answer the question of opening/starting at a particular row.

I'm also searching for a nicer way to do this, so far here's what I have:

function parse_data($skip_rows = 0){
  $record_number = 0;
  while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
    if (++$record_number <= $skip_products) continue;
    // do work
  }
}

Works, but I'm sure there's a nicer way.

EDIT: found a similar question: How do I open a file from line X to line Y in PHP?

Better to use: SplFileObject

Adam
  • 31
  • 5