Failed to read .CSV file

1

Dear, I have the following code, where I read a .CSV file and show it in a table. It even does the proposed, however I get the error Notice: Undefined offset: 1 at the end of the file. This for all arrays, minus 0

How to resolve this error?

<table id="data-table" class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Nome</th>
            <th>Usuário</th>
            <th>Email</th>
            <th>Perfil</th>
        </tr>
    </thead>
    <tbody>
        <?php
            $linhas = fopen ("teste.csv", "r");

            while (!feof ($linhas))
            {

                $ponteiro = fgets($linhas, 4096);

                $valores = preg_split("[;]",$ponteiro);
                echo "<tr>";
                echo "<td>".$valores[0]."</td>\n 
                      <td>".$valores[1]."</td>\n
                      <td>".$valores[2]."</td>\n
                      <td>".$valores[3]."</td>\n
                      <td>".$valores[4]."</td>\n
                      <td>".$valores[5]."</td>\n";
                echo "</tr>";     
              }

              fclose ($linhas);
              echo "</table>";
        ?>
    </tbody>
</table>
    
asked by anonymous 11.07.2018 / 21:50

1 answer

3

You can treat this warning by setting a default array if the preg_split() result is not as expected. Basically make sure it is null and assign the default array.

Other alternatives to preg_split() are explode() and str_getcsv()

$valores = preg_split("[;]",$ponteiro);

if(count($item) === 1 && is_array($item)){
   $valores = array_fill(0, 6, 'valor padrão');
}

You can better organize how to generate the table with a template and with the help of vprintf() , it receives two arguments the first is the template (string) with the placeholders ( %s ) and the second one must be an array, what the function does is to replace the %s with the repectivo element of the array this is made of < strong> positional form ie the first %s is replaced by the value of the first element of the array.

At the end your code is:

$template = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>';

while(!feof($linhas)){
   $valores = preg_split("[;]",$ponteiro);

   if(count($valores) === 1 && is_array($valores)){
      $valores = array_fill(0, 6, 'valor padrão');
   }
   vprintf($template, $valores);
}
    
11.07.2018 / 22:01