Skip First Line of Fgetcsv Method

Skip first line of fgetcsv method

try:

$flag = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
// rest of your code
}

Why is fgetcsv skipping the first row?

You've got an extra call to fgetcsv() before the loop begins - this will be fetching the first row and then discarding it, which means the loop will start on the second row.

Just remove this line and it should work correctly

$data = fgetcsv($handle, 1000, ",");

How to skip the n first lines with PHP function fgetcsv() or fopen()?

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.

Removing first line of CSV in PHP?

Call fgetcsv one more time before the loop starts.

PHP dynamically create CSV: Skip the first line of a CSV file

As you are keeping track of the row number anyway, you can use continue to skip the rest of the loop for the first row.

For example, add this at the start of your while loop (just above $num = count($data)):

if($row == 1){ $row++; continue; }

There are other ways to do this, but just make sure that when you continue, $row is still being incremented or you'll get an infinite loop!

Skipping First ROW of CSV File Data

I little bit changed your code, but it should work:

<?php

//if ($_FILES['csv']['size'] > 0) {
if (!empty($_FILES['csv']['size']) && $_FILES['csv']['size'] > 0) {
//get the csv file
$file = $_FILES['csv']['tmp_name'];

$row = 0;

if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

$row++;

if($row == 1) continue;

if ($data[0]) {
mysql_query("INSERT INTO mbet_football (TIME, TEAMS, HOME, DRAW, AWAY) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."'
)
");
}

}
fclose($handle);
}

//redirect
header('Location: mbetf.php?success=1'); die;

}

?>


Related Topics



Leave a reply



Submit