0

I have a somewhat irregularly structured CSV file I'm reading with fopen() and fgetcsv(). The first 5 lines are to be discarded.

Is there an efficient way to discard those 5 lines? What I have now is:

$fp = fopen($path,'r');
fgets($fp);fgets($fp);fgets($fp);fgets($fp);fgets($fp);

which gets the job done, but seems dirty.

3
  • 1
    With SPLFileObj you can do seek with line numbers. Without it you have to know the byte values Commented Aug 14, 2019 at 16:38
  • @ArtisticPhoenix Do you mean seek()? Commented Aug 14, 2019 at 16:39
  • Yes - Seek. with fseek you need the byte offset, which isn't workable. it's pretty trivial though. There is actually a trick with $File->seek(PHP_INT_MAX); $end = $File->key(); $File->rewind() that can give you the line total much faster then iterating through it.... :0} Commented Aug 14, 2019 at 16:41

1 Answer 1

6

So like this

 $CSV = new SplFileObject($file);
 $CSV->seek(5);
 $row = $CSV->fgetcsv();
Sign up to request clarification or add additional context in comments.

1 Comment

Only a hint: There is a difference between skip 5 text lines (request of the OP) and skip 5 table rows offered here. Maybe the OP wants this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.