How to split file for import

Asked

Viewed 26 times

0

I have a file that has no data separation and I need to insert it in the database, how can I import it.

For example, the file is like this:

931398401312 

I want to divide it into 4 columns, example:

|column1|column2|column3|column4|
|931    |3984   |01     |312    |

My code:

$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

$dados = file($arquivo_tmp);

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode(',', $linha);
    var_dump($valor);

    $column1 = $valor[0];
    $column2 = $valor[1];
    $column3 = $valor[2];
    $column4 = $valor[3];

    $result_usuario = "INSERT INTO teste (column1, column2, column3, column4) VALUES ('$column1', '$column2', '$column3', '$column4')";

    $resultado_usuario = mysqli_query($conn, $result_usuario);  
}
  • What is the divide pattern? Is it always 3, 4, 2 and 3 numbers? or can it change?

  • Yes, the pattern is this.

  • basically substr( $linha, $coluna, $largura ) - more details on the link above - Example: in your case: $column3 = substr( $linha, 7, 2 );

  • @Bacco I need to create a $row variable for each column? type $line1 = $column1...

  • yes, and each with a different start and width value. I gave an example of line 3 for you to see the values (starts at position 7, width 2)

  • Instead of $value I’ll use the substar then?

  • yeah, and there’s nothing exploding, and Trim tb is not for

  • Okay, thank you very much!!!!

Show 3 more comments
No answers

Browser other questions tagged

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