1

I read in a csv file by using a while loop:

while (($data = fgetcsv($handle, null, ",")) !== FALSE) 

and i want to skip the first row because this is the title row and i want to display on the screen "first line skipped".

if($data[0]=="title")
echo "Title row..skipping<br />";  
else
//do stuff

The problem is since its in a while loop it prints out "Title row...skipping" a bunch of times shown here:

Checking row 0...
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Checking row 1...

what should i do so it only prints it out once? does it have something to do with php's output buffering?

2
  • Your output looks really odd. Are you sure your csv file is formatted correctly? Commented Jul 5, 2010 at 5:34
  • 1
    Post more code. Your problem isn't in the part that we can see. Commented Jul 5, 2010 at 5:44

4 Answers 4

1

Or call fgetcsv($handle, null, ",") once without assignment, to move the handler forward by one line:

fgetcsv($handle, null, ",");

while (($data = fgetcsv($handle, null, ",")) !== FALSE) {
    // do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

0
if($data[0]=="title") {
  if (!$skipped) {
    echo "Title row..skipping<br />";
    $skipped = true;
  }
}
else
//do stuff

1 Comment

clever ;) i should have thought of that
0

If you know for a certain that you only need to skip the first line then;

if(!$skipped)
{
    echo "Title row..skipping<br />";
    $skipped = true;
}
else
//do stuff

1 Comment

Note: Aspired from Ast's answer ;P
0

I think it'd be more elegant to use foreach:

foreach data as item {
  if (item == "title") {
   echo "Skipping title<br/>";
  }
}

How you have it now, you are checking if (data[0] == "title") every time you loop. data[0] will always equal "title", so it will always evaluate to true. You could increment an $index variable and do something like if (data[$index] == $title) then $index++ near the bottom of the loop, but why do that when foreach will essentially do that for you.

Comments

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.