fgetcsv open at specific row?
Is there a way to use fgetcsv to open on a particular row?
I have a r开发者_JAVA百科eally 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?
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.
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
精彩评论