Playing more than one txt field within the database

1

Colleagues.

I'm wanting to get the data from a txt file that contains the user's name and registration. Ex.:

Fernando Pessoa; 000011;
Ruth Cardoso; 000012;
....

When trying to get it this way:

    $diretorio = 'arquivos/';
    $arquivos = $diretorio . $_FILES['dados']['name'];

    if (move_uploaded_file($_FILES['dados']['tmp_name'], $diretorio . $_FILES['dados']['name'])) {
            $ler = fopen($arquivos,"r");
            $conteudo = fread($ler,filesize($arquivos));
            $dividir = explode(";",$conteudo);

              foreach($dividir as $valores){
                   echo $dividir[0]." => ".$dividir[1]."<br>";
                   // aqui faço o cadastro
           }
    }

It returns only the first name and registration number repeating according to the total amount of data registered in the txt. If you have 30 names and registrations, you are bringing 30 times Fernando Pessoa 000011 and not the other data

    
asked by anonymous 31.07.2016 / 18:34

2 answers

1

There are two points where it is failing:

  • The explode first would have to be by line break (\ n), and only then by ';'

  • Correct version:

    ...
    $dividir = explode("\n",$conteudo);
    foreach($dividir as $valores){
        $exp = explode(';', $valores);
        if(isset($exp[1])) {
            echo $exp[0]. " => ".$exp[1]."<br>";
            // aqui faço o cadastro
        }
    }
    fclose($ler);
    
        
    31.07.2016 / 18:51
    0

    This happens because you are accessing a fixed value of array and not the current element of the iteration.

    Change: $dividir[0] and $dividir[1] by $valores[0] and $valores[1] .

    How to do this has already been explained in the Miguel response, here's another alternative:

    $diretorio = 'arquivos/';
    $arquivo = $diretorio . $_FILES['dados']['name'];
    
    if (move_uploaded_file($_FILES['dados']['tmp_name'], $arquivo)) {
      $conteudo = file_get_contents($arquivo);
      $linhas = explode("\n", $conteudo);
    
      foreach($linhas as $linha){
         if (empty($linha)){
           continue;
         }
      list($nome, $id) = array_map('trim', explode(";", $linha));
    
      echo "Nome: $nome - Matrícula: $id\n";
      // Fazer o cadastro...
    }
    
    • file_get_contents() is used instead of fopen() to deal with the file.
    • The function trim() is to eliminate white space between the ; and the numbers.
    31.07.2016 / 19:30