Serge111
Serge111

Reputation: 339

PHP Write to file multiline

This is my first time touching PHP so what seems like it should be a simple task has been a fairly long project for me so far between the google searching and trial and error, but I'm on the home stretch with one minor issue.

I'm writing a form, essentially for case notes, so I can fill in the fields, hit submit, and it puts everything into the appropriate case note template, and writes it to a file to serve as a local backup so I don't have to do that manually.

Now I have the following section on my form for case notes, which likely contain multiple lines, paragraphs, etc

Case Comments: <br>
<textarea name="comment" rows="10" cols="60"></textarea>
<P ALIGN="right"><input type="submit" name="Submit"></P>

Then in the form output page, I have the following. after some searching i found that to get it to output, i ended up needing to add the nl2br() for the comments to retain the formatting

<?php $comment = nl2br($_POST["comment"]);
echo $comment; ?><br>

I then have the following to write it out to a file

$txt = "C:\path\to\casenotes.txt";
$fh = fopen($txt, 'a');
fwrite($fh,$comment.PHP_EOL);
fclose($fh)

This writes everything out just fine, mostly. The problem is, the outputted test file ends up with html line break codes between the line breaks in the comments section, which is what I'm trying to remove if at all possible now. this is what I'm getting below

fsthyrew h<br />
<br />
asdfsaf<br />
<br />
<br />
asfd

Maybe someone can help point me in the right direction here?

Upvotes: 1

Views: 6606

Answers (1)

Barmar
Barmar

Reputation: 780798

Do:

fwrite($fh, $_POST['comment'].PHP_EOL);

This will write the original comment text, without the translation of newline to <br/> that nl2br() does.

BTW, you can condense those 4 lines to write the file into just:

file_put_contents($txt, $_POST['comment'].PHP_EOL, FILE_APPEND);

Upvotes: 7

Related Questions