Failed to read file. CSV

Asked

Viewed 71 times

1

Dear, I have the following code, where I read a file . CSV and show it in a table. It even does the proposed, however returns me the error Notice: Undefined offset: 1 at the end of the file. This for all matrices, except 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>

1 answer

3


You can treat this Warning by setting a default array if the result of preg_split() not expected. Basically check if it is null and assign the default array.

Other alternatives to preg_split() sane 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 takes two arguments the first is the template (string) with placeholders (%s) and the second must be an array, what the function does is to replace the %s by the repective element of the array this is made of positional shape namely 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);
}
  • I understand that it is necessary to validate if it is null, it was validating through isset(), however unsuccessful too. With this solution proposed by you I did not have effectiveness too...

  • @Willianlima edited the answer, I forgot that if the delimiter is not found in the string, it is returned anyway and not as false.

  • In this last way, it worked, the last line was marked as 0. It is not yet ideal, but it is already a haha beginning. Thanks Edit: I made a change to the code, it’s perfect now!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.