Playing more than one txt field inside the database

Asked

Viewed 46 times

1

Colleagues.

I am wanting to get the data from a txt file that contains the name and registration of the user. Ex.:

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

Trying to take it that 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 repeating as the total amount of data registered in txt. If you have 30 names and registrations, is bringing 30 times Fernando Pessoa 000011 and not the other data

2 answers

1


There are two points where you are failing:

  1. The explosion would first have to be by line break ( n), and only then by ';'

  2. within your foreach is always echo the same data ($dividir[0], $dividir[1])

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);
  • Perfect Miguel. It worked. Thank you !

  • @Fox.11 After reading the file close the Handle with fclose($ler).

  • You’re welcome @Fox.11. I’m glad

  • @zekk, obsessed I’ll edit accordingly, forgot

0

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

Alter: $dividir[0] and $dividir[1] for $valores[0] and $valores[1].

How to do this has already been explained in answer from Miguel, follows below 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...
}
  • Is used the file_get_contents() instead of fopen() to deal with the file.
  • The function trim() is to eliminate the white space between the separator ; and the numbers.

Browser other questions tagged

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