Output Text File with Line Breaks in PHP

Output text file with line breaks in PHP

To convert the plain text line breaks to html line breaks, try this:

    $fh = fopen("filename.txt", 'r');

$pageText = fread($fh, 25000);

echo nl2br($pageText);

Note the nl2br function wrapping the text.

Writing TXT File with PHP, Want to Add an Actual Line Break

Sounds to me like you might be using single quotes, i.e. '\n' rather than "\n".

If you wanted to continue with a single quotes bias (as you should!), two options:

file_put_contents('/path/to/file.txt', 'Hello friend!
This will appear on a new line.
As will this');

// or

file_put_contents('/path/to/file.txt', 'Hello friend!'."\n".'This will appear on a new line.'."\n".'As will this');

Line break not working when writing to text file in PHP

If you want to open the file in Windows notepad, you must use Windows line breaks: \r\n

Extra line breaks in output to file

Try this before writing it to the file:

$content = preg_replace('#\r\n?#', "\n", $content);

how to read a txt file with spaces and line breaks into it

Try:

$flatfile = file_get_contents('database-001.txt');
echo nl2br($flatfile);

What is happening is, the browser doesn't understand \n. You should use <br> instead. nl2br transforms all classic new lines \n to <br>.

You can easily see this with the following example:

$str1 = "regular \n newline";
$str2 = "browser <br> newline";
echo str1;
echo str2;

Unexpected PHP line breaks when writing to a file

What you have is linebreak characters that you can't see but that are being sent within the $_POST value, as mentioned by Marc B.

The work around to this is to remove the PHP End of Line Characters, which are handily referenced as PHP_EOL.

(Personally I would also reference array keys in single quotes as double quotes effects quote references and such within the array values)

So

$_POST['msg'] = str_replace(PHP_EOL, '', $_POST['msg']);
// str_replace($search,replace,subject);

This will remove system used line breaks from the string, before you can then save to the file. You can additionally replace standard line break [type character]s such as \n and \r (\r is not actually a linebreak as such, exactly) in case they're different from the PHP_EOL value :

Also suggested you save the changes as another variable rather than the original POSTed data.

$breaks = array("\n","\r",PHP_EOL);
$strippedMessage = str_replace($breaks, '', $_POST['msg']);


Related Topics



Leave a reply



Submit