Question

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);
}
Was it helpful?

Solution

Going from your comment, and from the idea that the actual data is temperatures (i.e. 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));

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top