Validate number of fields and have records csv file

1

I want to validate:
1) That the CSV file has the number of fields that are required (in my case 6).
2) That the CSV file has at least one record to work with.
I do not need to validate that the file exists.
The following code shows the number of fields per record that the CSV file has.

<?php
$fila = 1;
$gestor = fopen("C:\archivo.csv", "r")
    while (($datos = fgetcsv($gestor, 1000, ",")) !== FALSE) {
        $numero = count($datos);
        echo "$numero de campos en la línea $fila </br>";
        $fila++;
    }
fclose($gestor);
?>

I want to simplify the code to achieve what I indicated. The file contains a header.

    
asked by Piropeator 07.02.2017 в 03:05
source

1 answer

1

If you want to create a function that makes the following checks:

  • More than one data line.
  • All records must have six fields.

This function could help you:

function comprobar_csv($archivo) {
  $n = 0;
  if (!file_exists($archivo)) {
    /* Decidir qué hacer en caso de que no exista el archivo */
    return false;
  }
  $fh = @fopen($archivo, 'r');
  if ($fh === false) {
    /* Decidir qué hacer en caso de error de apertura */
    return false;
  }
  while (($datos = fgetcsv($fh, 1000, ',')) !== false && ++$n) {
    /* En caso de no tener 6 campos cerramos y salimos */
    if (count($datos) != 6) {
      fclose($fh);
      return false;
    }
  }
  fclose($fh);
  /* Comprobamos que tenga al menos una línea */
  return $n > 0;
}
/* Ejemplo de uso */
var_dump(comprobar_csv('ejemplo.csv'));
    
answered by 07.02.2017 / 08:20
source