Save positions of a text file in variables using PHP

-1

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

01 : $ cnpj = Position 03 to 16, $ number = Position 17 to 16
02 : $ CodeBarras = Position 29 to 35
03 : $ Quantity = Position 03 to 16

  

Since the 02 record can have more than one row, it can handle items in an order.

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

    
asked by anonymous 18.07.2018 / 21:30

1 answer

0

Railam, Use the file_get_contents function together with a explode

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

After this use the substr

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

You need to confirm what you are returning in the variables.

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

If the pattern you follow is that of the file you enter, follow the 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);
    
18.07.2018 / 21:39