unable to put new line in this code
i try "\n" , <br/>
but not working
i want that when this docoment write in the file data.txt there should be new line
between First name, last name and email

<?php
$file = fopen("data.txt", "a+");
fwrite($file,"First name:$_POST[fname] Last name:$_POST[lname] Email:$_POST[email] Comment:$_POST[comment]");
?>

Dani AI

Generated

Good to see this was resolved for after 's suggestion. The underlying issue is just line-ending handling: different platforms expect different end-of-line bytes, so using a portable constant removes the guesswork (see the PHP_EOL note on the PHP manual: PHP_EOL).

A compact, safer pattern is to build a single text line, sanitize inputs, append a platform-correct line ending, and write with an atomic append/lock. Example approach:

$line = sprintf(
  "First name: %s, Last name: %s, Email: %s%s",
  htmlspecialchars($_POST['fname']),
  htmlspecialchars($_POST['lname']),
  filter_var($_POST['email'], FILTER_SANITIZE_EMAIL),
  PHP_EOL
);

file_put_contents('data.txt', $line, FILE_APPEND | LOCK_EX);

See file_put_contents and htmlspecialchars for details.

Extra tips: if you keep using fopen/fwrite, always fclose and use locking (flock) to avoid race conditions. Use quoted array keys like $_POST['fname'] to avoid notices and to be compatible with newer PHP versions. When showing the saved file in a browser, convert newlines to HTML breaks or wrap the text in a preformatted block (or use nl2br). and also suggested workable alternatives — chr()/OS-specific endings and HTML breaks — but the PHP_EOL + atomic append approach is simplest and most portable.

Recommended Answers

All 4 Replies

Uhh don't you just hit the enter button?
And if you want them lined down on the actual web page that you are creating. You can just put <br> before the beginning of each line.

commented: good +0

Try "\r\n" instead of just "\n" . \r is a carriage return.

Member Avatar for Member #334542

Concetenate the statements like below with the single quotes.

fwrite($fh, 'Look, Ma,'.chr(13).' I wrote a file! ')

It works perfect!

Try "\r\n" instead of just "\n" . \r is a carriage return.

Thanks Its working

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.