John Davidson

Read from nth row from a csv file in php

0 comments
Message:


This is my CSV file


1,100003,cs1aa,abc1
2,100004,cs1aa,abc2
3,100008,cs1aa,abc3
4,100009,cs1aa,abc4
5,100010,cs1aa,abc5
6,100011,cs1aa,abc6
7,100012,cs1aa,abc7
8,100013,cs1aa,abc8
9,100014,cs1aa,abc9
10,100015,cs1aa,abc10

Now i m using fgetcsv in while loop to read my csv files


 $file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
}

Is there a way in php to read this csv file from the nth line of the file ?

For eg, if n=5, then the loop should start reading from the 5th line of the file



My Answer:
Yes, you can achieve this by keeping track of the line number while reading the file using fgetcsv. You can use a counter variable to keep track of the line number and start reading from the nth line.

Here is an example code snippet to read the CSV file starting from the nth line:

php
$file = fopen('file.csv', 'r');
$n = 5; // nth line to start reading from
$lineNumber = 1;

while (($line = fgetcsv($file)) !== FALSE) {
if ($lineNumber >= $n) {
// Process the line starting from the nth line
// Example: echo the values in the line
echo implode(',', $line) . "\n";
}

$lineNumber++;
}

fclose($file);


In this code snippet, we have added a counter variable `$lineNumber` to keep track of the line number. We start reading from the nth line by checking if the current line number is greater than or equal to the specified value of `n`. If it is, we process the line (in this case, we are just echoing the values in the line).

Remember to close the file using `fclose($file)` after you have finished reading the file.

Rate this post

5 of 5 based on 9085 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us