3

How to skip first row and read upto five rows from csv in PHP

Hello,

I have following code in which I want to skip first row in csv that is headers of columns and read upto five rows of csv file.

Current code skip first row but display all records.

How can I achieve this ?

<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);

define('CSV_PATH', '/var/www/Products_upload_12499/'); // specify CSV file path

$csv_file = CSV_PATH . "skipfirstrow.csv"; // Name of your CSV file
$csvfile  = fopen($csv_file, 'r');

$counter = 1;
while ($data = fgetcsv($csvfile)) 
{
    if($counter==1) {
            $counter++;
            continue;
            }       }
    $days = trim($data[0]);
    echo "==>> " . $days."\n";
        if ($counter >= 6) {
        exit();
    }

}

?>
Nikita
  • 57
  • 1
  • 10

3 Answers3

1

You can create an if else conditional that only outputs the rows you want, and that breaks the while loop when you got all the rows you wanted:

$row = 0;
while ($data = fgetcsv($csvfile)) 
{
    $row++;//starts off with $row = 1
    if (($row>1)&&($row<6))//rows 2,3,4,5
    {
        foreach ($data as $cell)
        {
           echo "|  {$cell}  |";
        }
        echo "<br>";
    }
    else if ($row>=6)
    {
        break;
    }
}

You can replace the echo "| {$cell} |"; code with whatever you like the code to output.

Let me know if this worked for you.

Webeng
  • 7,050
  • 4
  • 31
  • 59
0

just skip first line by not equal assign != ,let me know is it work

$counter = 1;
while ($data = fgetcsv($csvfile)) 
{
    if($counter !=1) {
      $days = trim($data[0]);
      echo "==>> " . $days."\n";
      if($counter >= 6)
        break;
    }
    $counter++;
}
vp_arth
  • 14,461
  • 4
  • 37
  • 66
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
0

Yet another code to achieve this.
fgets used to skip lines to avoid excess csv parsing.

if (($f = fopen('test.csv', 'r')) === false)
  throw new Exception('File not found');

$skip = 1;
$length = 5;

for ($i = 1; $i < $skip; $i++) fgets($f); // skip first $skip lines
for ($i = $skip; $i < $skip + $length; $i++) {
  $row = fgetcsv($f);
  echo implode(', ', $row)."<br/>\n";
}
vp_arth
  • 14,461
  • 4
  • 37
  • 66