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

Asked

Viewed 1,774 times

1

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

The archive looks like this:

marcos
fulano
ciclano
beltrano

I need PHP to read this file, and generate a new one, but with ; at the end

Would look like this

marcos;
fulano;
ciclano;
beltrano;

Someone gives me a light, and I couldn’t find an example to read and change then record!

  • 1

    Names are separated by space or by line break?

  • @Juniornunes7, it was an error in formatting the question. Names are separated by line.

  • If you already have line breaks, why do you need the ; ?

2 answers

6


If you have separating 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);

This way you open the file you want to format with the fopen, you read the file with the fread and then use the str_replace to detect all the broken lines of the text read and replace by semicolon + space, staying in 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 will save the new file, if you do not have the right permissions the script will not work.

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

  • 1

    What if it is a compound name? The solution no longer applies. For example in question, it is separated by a line break, so you could add this option in your answer.

  • The question before was separated by space, because of the formatting, already corrected, I will edit the answer!

1

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

The only thing I changed was the line breaking 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);

Browser other questions tagged

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