开发者

How to make the header row be skipped in my while loop using fgetcsv?

开发者 https://www.devze.com 2023-01-30 03:21 出处:网络
I can\'t get the new code I\'ve written to skip the first row (header) as the code I was using before did (see bottom).

I can't get the new code I've written to skip the first row (header) as the code I was using before did (see bottom).

I'm not receiving any errors, but just can't get it to omit first row.

$file = fopen($uploadcsv,"r");
$column_headers = array();
$row_count = 0;
while(!feof($file)) {   
  if ($row_count==0){
    $column_headers = $file;
  } else {
    print_r(fgetcsv($file));
  }
  ++$row_count;
  }

fclose($file);

Below is the old source that skipped the开发者_开发知识库 header, for reference and comparison.

$handle = fopen($uploadcsv, 'r');
$column_headers = array();
$row_count = 0;
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
  if ($row_count==0){
    $column_headers = $data;
  } else {
    print_r($data);
  }
  ++$row_count;
}
fclose($handle);


Why even count? Just get the headers before looping.

$column_headers = fgetcsv($file);
while(!feof($file)) {
   ...

Also, you're only assigning the file pointer to the variable.


When $row_count is 0 you are not reading any row.

Change

if ($row_count==0){
    $column_headers = $file;  // just assigning file handle.
}

to

if ($row_count==0){
    $column_headers = fgetcsv($file); // read the row.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号