Read txt and generate a new com; at the end of each line

1

I created a system that imports the names generated in TXT, but the system interprets the ; at the end of each line and writes to the bank, but my client's commercial system exports the data without the ; ; in the end, the worst that is a telemarketing system that generates files of almost 5000 thousand names a day!

The file looks like this:

marcos
fulano
ciclano
beltrano

I need PHP to read this file, and generate a new one, however; in the end

It would look like this

marcos;
fulano;
ciclano;
beltrano;

Someone gives me a light, and I could not find an example that would read and change then serious!

    
asked by anonymous 11.11.2016 / 01:28

2 answers

6

If you have separated the names by line break you can use this here:

$file = fopen('./file.txt','r');
$document = fread($file, filesize('./file.txt'));
$formatedDocument = str_replace("\n", '; ', $document);

echo $formatedDocument;

fclose($file);

In this way you open the file you want to format with fopen , you read the file with fread and then use str_replace to detect all line breaks of the read and replace text by point and comma + space, getting the format you expect.

And to write to a new file you can use:

$newFile = fopen("./new-files/new-file.txt", "a");

$write = fwrite($newFile, $formatedDocument);

fclose($newFile);

NOTE: Pay attention to the write permissions of the folder you are going to save the new file to, if you do not have the correct permissions, the script will not work.

NOTE: If the names in the file to be read are separated by space, you can replace str_replace with str_replace(' ', '; ', $document); that will work correctly.

    
11.11.2016 / 12:08
1

Valew Junior, your answer gave me notion of how to work here, the system separates by; it will not be necessary to break the line, so I let it write one in front of the other, no problem, and it worked out

The only thing I changed was the line break from \ n to \ r

 $arquivo = "arquivo.txt";
$fp = fopen($arquivo,'r');
$document = fread($fp, filesize($arquivo));
$formatedDocument = str_replace("\r", ';', $document);
$escreve = fwrite($fp, $formatedDocument); 
fclose($fp); 
$arquivo_new = fopen("novo_".$arquivo, "w");
$texto = $formatedDocument;
fwrite($arquivo_new, $texto);
fclose($arquivo_new);
unlink($arquivo);
    
11.11.2016 / 16:18