[英]Read from nth row from a csv file in php
This is my CSV file这是我的 CSV 文件
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 im using fgetcsv in while loop to read my csv files现在我在 while 循环中使用 fgetcsv 来读取我的 csv 文件
$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? php 有没有办法从文件的第 n 行读取这个 csv 文件?
For eg, if n=5, then the loop should start reading from the 5th line of the file例如,如果 n=5,那么循环应该从文件的第 5 行开始读取
Just iterate and run fgets as many times as you need to.只需根据需要多次迭代和运行 fgets 即可。
<?php
$skip = 5;
$file = fopen('file.csv', 'r');
for($i = 0; $i < $skip && (fgets($tmp) !== false); $i++);
while (($line = fgetcsv($file)) !== FALSE) {
}
fgets
reads a single line from the file. fgets
从文件中读取一行。
Using fgets
means you won't spend any additional time parsing CSV when you don't need to.使用
fgets
意味着您不会在不需要时花费任何额外的时间来解析 CSV。
$skip = 5; $c = 1; $file = fopen('file.csv', 'r'); while (($line = fgetcsv($file)) !== FALSE) { if( $c++ < $skip ) { continue; } }
This should work as expected这应该按预期工作
$row = 0;
$start_from = 5; //starts from nth row, 5th row in this case
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
//skip if value less than $start_from row value
if($row<$start_from){
continue;
}
//else print, you can also do something else with this data
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Explanation解释
for
loop but you can use whatever is your use case.for
循环,但您可以使用任何您的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.