After opening CSV files with fopen()
, I'm currently skipping the three first lines of these files like this:
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
Is there a nicer method to skip the n first lines ?
After opening CSV files with fopen()
, I'm currently skipping the three first lines of these files like this:
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
Is there a nicer method to skip the n first lines ?
If you need to skip more than a handful of lines, simply add one instance of the "throw-away read" code you already have inside a for
loop. Number of loops equals lines skipped (e.g. 8 lines):
for ($i = 0; $i < 8; $i++) {
fgetcsv($file, 0, ';');
}
Do this before you begin your main while
loop getting the CSV lines you care about. You could turn the loop into a utility function -- if you find yourself doing this often at different skip lengths.
function fskipcsv_lines($handle, int $lines) {
for ($i = 0; $i < $lines; $i++) {
fgetcsv($handle, 0, ';');
}
}
Simple enough. Same construct applies for the "dumb" repetition of any other function you don't need to get a a return value from, that simply needs to be called N times.
P.S. Don't place the "skip line" check routine inside your main CSV iteration loop. Why? Because the check (e.g. $row < 3
; or in_array($row, $skips)
) would happen at each loop iteration. Suppose you need to read 100,000+ lines, the overhead will start adding up, unnecessarily burdening each loop iteration for the first (now past) few lines' sake.
Your are doing right, but this code may help if you are going to skip many. :
$skippTheseLines = array(1,2,3);
$i = 0;
$totlLines= 10000;
while (($emapData = fgetcsv($file, $totalLines, ";")) !== FALSE) {
if(in_array($i, $skippTheseLines)) {
continue;
}else{
// rest of your code
}
$i = $i + 1;
}
Check out this code. Similar questions: skip first line of fgetcsv method in php
$file = fopen('example.csv', 'r'); // Here example is a CSV name
$row = 1;
$number_to_skip = 3
while (($line = fgetcsv($file,0, ",")) !== FALSE) {
// $line is an array of the csv elements
if($row < $number_to_skip)
{
$row++; continue; // continue is used for skip row 0,1,2
}
print_r($line);
}