1

I have a code where a csv file is uploaded ,the data is extracted from it and uploaded to database.Everything works fine,but how can i skip the empty rows and continue reading the rows with data in it.

This is the code where i extract data from csv file

if (($source = fopen( $csv_file, "r")) !== FALSE)
{
//read data from excel
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
    $question=$data[0];
    $point=$data[1];
    $header=$data[2];
    $footer=$data[3];
    $type_value=$data[4];
    $group_name=$data[5];
        echo $question;

}// while end

}
1
  • if (empty($data[0])) { continue; } something like this at the start of the while loop? Commented Feb 14, 2017 at 14:16

4 Answers 4

1

If you use PHP's SplFileObject instead of the basic fgetcsv() function, it has built-in options to skip empty lines:

$file = new SplFileObject($csv_file);
$file->setFlags(SplFileObject::READ_CSV SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
foreach ($file as $data) {
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thats nice..Let me try that
1
if ($data[0] == NULL)
         continue;

This is because fgetcsv returns a non-empty array with a null element inside.

1 Comment

With this, if the first elemnt is empty, it skips the line altogether. (e.g: [, 1, 2]). Better line would be: if (count($data)<=1 & !$data[0]) continue;
0

Try it with

if ($data === null) continue;

I didn't test it, but I sthink it should work.

Comments

0

Try this

if (($source = fopen( $csv_file, "r")) !== FALSE)
{
// read data from excel
    while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
    {
        if ((string) $data[0] != '0' and empty($data[0]))
        {
            continue;
        }

        $question   = $data[0];
        $point      = $data[1];
        $header     = $data[2];
        $footer     = $data[3];
        $type_value = $data[4];
        $group_name = $data[5];

        echo $question;
    }
}

2 Comments

As there are many columns,a large set of conditions will be required right?
i minimized the condition. the reason i put (string) $data[0] != '0' in condition because empty() function treats 0 as empty value also

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.