How to skip line when reading a txt in PHP?

Asked

Viewed 234 times

0

I am working on a system that will run on the Web, using PHP and html and I have a question.

My program reads the txt and separates the information through the delimiter ; writes to an array and saves the information I want inside the database.

What I need is for the program to skip the first line of this txt and read from the second line.

txt has this format:

ID;CODE;NAME;PRODUCT;TIPO_MOV;COTAS;VALOR;NUM_NOTA;FORMA 1;;Test;00.000.000/0001-00;A;0.00000000;80000;TED

What I save is only the information of the second line how can I do to skip the first line?

My code:

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


$dados = file($arquivo_tmp);

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

$id = $valor[0];
$Plataforma = $valor[2];
$Produto = $valor[3];
$Tipo_mov = $valor[4];
$Valor = $valor[6];
$Forma = $valor[8];
$Numero_banco = $valor[9];
$Numero_Agencia = $valor[10];
$Numero_conta = $valor[11];
$Digito_verif = $valor[12];
$Tipo_conta = $valor[13];
$cnpj = $valor[21];
  • basic question.. the file follows this pattern always ? never changes ? if that’s it you can start by picking up only even lines and ignoring odd lines ? sera q is not simpler that way ?

  • If $dados has the file lines, use array_shift to remove the first element.

  • @ederwander I don’t think I can take only the even lines, because it arrives file with more lines. The received file is always in this pattern.

  • @Woss Certo, I researched this array_shift, I will try to use it. If data has the line it removes the entire line not only the first index by logic. Thanks for the suggestion.

2 answers

0


Resolution:

<?php
session_start();

include_once("conexaoFin.php");

$arquivo_tmp = $_FILES['arquivoTxt']['tmp_name']; // tmp_name é o caminho do arquivo

$dados = file($arquivo_tmp);
$TiraLnha = array_shift($dados);

foreach($dados as $linha){
    $linha = trim($linha);

    $valor = explode(';', $linha);

var_dump($valor);
}

?>

0

Code below explains:

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


$dados = file($arquivo_tmp);
$cabeçalho = dados[0]; // <- guardando cabeçalho
$dados = unset($dados[0]); // <- tirando ele dos dados
foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode(';', $linha);
    var_dump($valor);

$id = $valor[0];
$Plataforma = $valor[2];
$Produto = $valor[3];
$Tipo_mov = $valor[4];
$Valor = $valor[6];
$Forma = $valor[8];
$Numero_banco = $valor[9];
$Numero_Agencia = $valor[10];
$Numero_conta = $valor[11];
$Digito_verif = $valor[12];
$Tipo_conta = $valor[13];
$cnpj = $valor[21];

Browser other questions tagged

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