How to create a textfile and write to it, coverting newline's
TAGS: PHP, fopen, fwrite, nl2br, convert, newline, break


If we want to read the 'file.txt' that we created in the posting 'How to create a textfile and write to it', we will notice that the newlines that we inserted in the string, written to the file does not show in the webbrowser. So what can we do about that?
PHP comes with a small solution to that problem, it is called 'nl2br' (newline to break), it will convert the newline into a HTML
. Here I show how to do this. It is very simple, we just add one line, the one that is highlighted in this snippet. Then we write HTML breaks instead of newlines.

<?php 
$String = "Hello World!\n\nThis is a test in creating a textfile, and writing to it."; 
$String = nl2br($String);

$mytextfile = fopen("file.txt", "a") or die("An error occurred. <A HREF='formmail.php'>Send webmaster a message</A>"); 

fwrite($mytextfile, $String); 
fclose($mytextfile); 

echo 'Super, you have created a file'; 

?>


This was a way to handle linebreaks.