Save positions of a text file to variables using PHP

Asked

Viewed 48 times

-1

I need to read a text file to later save them in the database, where values are named in type records :

01: $cnpj = Position 03 to 16 , $numero = Position 17 to 16
02: $Code = Heading 3 to 15 , $quantidadef = Heading 29 to 35
03: $quantity = heading 03 to 16

Where the record of the type 02 may have more than one line as it handles items from an order.

The attached image demonstrates the layout of the file to be read:

ARQUIVO DE TEXTO MENCIONADO

1 answer

0


Railam, Use the function file_get_contents together with a explode

$linhas = explode("\n", file_get_contents(caminho/do/arquivo));

After that use the function replace

$cnpj = substr($linhas[0],3,16);

You need to confirm what is returning in the variables.

But this would be done in all cases listed just need to hit the positions of "Cut"

If the default you follow is the one of the reported file follow examples to get the other records.

$total = count($linhas);


$quantidade = substr($linhas[($total - 1)],3,16);

for ($i=1; $i < $total-2; $i++) { 
    $CodigoBarras[] = substr($linhas[$i],3,15);
    $quantidadef[] = substr($linhas[$i],29,35);
}

var_dump($CodigoBarras,$quantidadef);
  • I forgot to tell you, but the lines you search for, example 1, will always be a low index, so if it is line 13 it will be index 12 in the generated array ($lines)

  • Right ! I tested it here and it partially assisting me , my problem now is with the registration 02 if it appears more than once in the file . as these are items . . .

  • Could I put an example of what it would be like with more than one barcode?

  • The following file contains the entry type 02: https://pastebin.com/raw/fTmKBp4r

  • Got it, so it’s pretty simple. Take the total of records in the $lines array, remove 2 (the first and last, always default). And start a loop that runs through the $lines array from index 1 to the full size of $lines - 2. I’m going home at the moment. From there I can be sending an example if you prefer.

  • Already for the last record just get the total and discount one you will get normal.

  • I will be grateful if you help me with this , I am trying here also , I thank you for your help. Grateful.

  • Sorry it took so long, I just got back on PC

  • Railam, the answer worked?

  • Hello, right , I made some modifications to meet me, but it was all right ! Thank you my friend.

  • Good, please inform as answered the question.

Show 6 more comments

Browser other questions tagged

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