Write to txt file with PHP

Asked

Viewed 2,019 times

2

I have a file txt but is missing the nome in several lines of the file, I would like to put the name according to the order number.

The logic would be to check the order number of the line that is without the name in case the request 203885, find another line that has the same order number and that has a name, take this name and copy it to all equal order numbers. However, order numbers that are not equal have different names. The column that represents requests is column 2.

Original File txt:

100400;205537;30141;BALCAO 1 PORTA PER 400X670X500;MDF BP BRANCO;6;79281905;NOME1;0205537006
100400;203885;50058;PAI OPC EDIT LARGX ALTX 25;BLANCHE#695#320;18;79283198;NOME;0203885018
100400;205537;100001;EMBALAGEM DE FERRAGENS DIVERSAS;                                ;35;79283215;                              ;0203885035
100400;203885;101619;EMBALAGEM DE FUNDOS DORMITORIO;                                ;36;79283216;                              ;0203885036

After modified it should look like this:

100400;205537;30141;BALCAO 1 PORTA PER 400X670X500;MDF BP BRANCO;6;79281905;NOME1;0205537006
100400;203885;50058;PAI OPC EDIT LARGX ALTX 25;BLANCHE#695#320;18;79283198;NOME;0203885018
100400;205537;100001;EMBALAGEM DE FERRAGENS DIVERSAS;                                ;35;79283215;NOME1;0203885035
100400;203885;101619;EMBALAGEM DE FUNDOS DORMITORIO;                                ;36;79283216;NOME;0203885036

Just modify in the file is not necessary to print on screen.

  • the name will be the same for everyone and should be in this empty space?

  • If I understood correctly, I would have to compare $linha[6] if there is no take the previous value (which is in another variable) . you just want to print it on the screen?

  • 1

    I want to change in the same file print on canvas is not necessary, but it is in the empty space that should contain the name.

  • describe which column represents the order codes

2 answers

2

Test script

/*
Esse array simula a relação entre os códigos dos pedidos e os nomes
*/
$orders = array(
    '205537' => 'FULANO 1',
    '203885' => 'FULANO 2'
);

/*
Dados para teste
*/
$data = '100400;205537;30141;BALCAO 1 PORTA PER 400X670X500;MDF BP BRANCO;6;79281905;NOME;0205537006
100400;203885;50058;PAI OPC EDIT LARGX ALTX 25;BLANCHE#695#320;18;79283198;NOME;0203885018
100400;203885;100001;EMBALAGEM DE FERRAGENS DIVERSAS;                                ;35;79283215;                              ;0203885035
100400;203885;101619;EMBALAGEM DE FUNDOS DORMITORIO;                                ;36;79283216;                              ;0203885036';

/*
Essa é a parte que interessa.
*/
$arr = explode("\n", $data);
foreach ($arr as $k => $v) {
    $csv[$k] = str_getcsv($v, ';');
    $csv[$k][7] = $orders[$csv[$k][1]];
    $csv[$k] = implode(';', $csv[$k]);
}
$data = implode("\n", $csv);
echo $data;

Final implementation

$orders = array(
    '205537' => 'FULANO 1',
    '203885' => 'FULANO 2'
);

$file = '/local/do/arquivo.txt';
$arr = file($file);
foreach ($arr as $k => $v) {
    $csv[$k] = str_getcsv($v, ';');
    $csv[$k][7] = $orders[$csv[$k][1]];
    $csv[$k] = implode(';', $csv[$k]);
}
file_put_contents($file, (implode("\n", $csv));

Be aware that this is not optimized for heavy files, with more than 100MB, for example.

  • Only here comes the problem, I won’t be able to manually set the NAME there in the replace it has to be dynamic. Because the name varies for each order number. Each order is not always the same. For example the order 203885 will have the name "teste1" and the order 205537 "teste2" so for all orders 203885 has to fill with the name "teste1" and for the 205537 "teste2".

  • I’ve already edited the question, it’s in the second paragraph.

  • 1

    See if it’s clearer now.

1


Kelvin could do the following, show how it is in txt and also how you want the result, so I can understand and help better. A while ago I made a post about UTF-8 fix which analyzes a file in question and fixes and creates a new one, I’ll leave the link here may be useful. http://www.bulfaitelo.com.br/2016/10/como-reparar-problema-com-caracteres-em.html

I made a code that checks the txt generates an array with all the numbers and their names together with a new vector with all the information, after that I run again the vector already correcting the field that is missing, thus correcting the names. and finally create again the items separated by ";"

Watch out for the code:

<?php

$file_name = "IMP.txt";

$file = fopen($file_name, "r") or die ("Arquivo não encontrado!");
$file_output = fopen("Output_".$file_name, "w") or die ("Arquivo não criado!");
// Gerando o vetor para tratamento
while(!feof($file)){    
    $strAnalise =  fgets($file) ;
    $strAnaliseArray = explode(";", $strAnalise);
    if(trim($strAnaliseArray[7]) != ''){
        $ArrayChaveNome[$strAnaliseArray[1]] = trim($strAnaliseArray[7]);
    }
    $strArrayDados[]=$strAnaliseArray;
}
// Corrindo o vetor;
foreach ($strArrayDados as $key => $value) {
    if(trim($value[7]) == ''){
        if(array_key_exists($value[1], $ArrayChaveNome)){
            $strArrayDados[$key][7]= $ArrayChaveNome[$value[1]];
        }
    }
}
// retornando a ";"
foreach ($strArrayDados as $key => $value) {
    $resultPontoVirgula.= implode(";", $value);
    $resultPontoVirgulaToTxt= implode(";", $value);
    fwrite($file_output, $resultPontoVirgulaToTxt);
}   
// var_dump($strArrayDados);
// var_dump($strAnaliseArray);
var_dump($resultPontoVirgula);

fclose($file_output);
fclose($file);

?>

Browser other questions tagged

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