简体   繁体   中英

Check for header in csv and ignore header in php

I would like to check if csv file contain a header and ignore the header.

I have to do a check if the first column is not a character

csv file has format : avgTemperature, minTemperature, maxTemperature

 $f = fopen("./uploads/" .$filename, "r"); $string = "avgTemperature"; if (fgetcsv($f)==$string){ // read the first line and ignore it fgets($f); } 

I assume your complete code uses a loop ( while or for ).

As such, you have a few options.

  • Simply skip the first row always .
  • Use logic to test for the header row then skip.

Either way, continue is the key piece.

PHP pseudo code:

while (…) {
  if ($row == $header_row) {
    continue;
  }

  // data rows
}

UPDATE

The logic for determining if the first row is a header row seems like a better solution in your case. You could use the following to test for that.

if ($row[0] == 'avgTemperature') {
  // header row
}

Note: This makes the assumption that the first column of data is avgTemperature and it's header is avgTemperature . Adjust as necessary.

Going from your comment, and from the idea that the actual data is temperatures (ie numeric data), if you do have headers, then they will be text strings and not numbers. Therefore you can do something like this:

$f = fopen("./uploads/" .$filename, "r");

if(!($data = fgetcsv($f))) {
    return;    //most likely empty file
}

if(!is_numeric($data[0])) {
    //this is your header line - skip it - and read the next line
    $data = fgetcsv($f);
}

while($data) {
    //process a line of data
    ...
    //and read the next line
    $data = fgetcsv($f);
}

EDIT: An alternative version of the last loop would look like this:

do {
    //process a line of data
    ...
}
while ($data = fgetcsv($f));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM