I have a PHP script which retrieves the contents of a raw / plain-text file and I'd like to output this raw text in HTML, however when it's outputted in HTML all the line breaks don't exist anymore. Is there some sort of PHP function or some other workaround that will make this possible?
For example, if the raw text file had this text:
hello
my name is
When outputted in HTML, it will say:
hello my name is
Is there any way to preserve these line breaks in HTML? Thank you.
(If it helps, my script gets the contents of the raw text file, puts it inside a variable, and I just echo out the variable.)
There are several ways to do this:
Using file_get_contents()
and nl2br()
:
echo nl2br( file_get_contents( 'filename.txt'));
This won't solve special entities like <>&
, you'll need to use htmlspecialchars()
echo nl2br( htmlspecialchars( file_get_contents( 'filename.txt')));
Perhaps better solution would be loading entire file into array with file()
and iterate trough all elements (you'll be able to put lines into table or so in future)
$data = file( 'filename.txt');
foreach( $data as $line){
echo htmlspecialchars( $line) . '<br />';
}
And if you need to process large amount of data it'd be best to do it sequentially with fopen()
and fgets()
:
$fp = fopen( 'filename.txt', 'r') or die( 'Cannot open file');
while( $line = fgets( $fp)){
echo htmlspecialchars( $line) . '<br />';
}
fclose( $fp);
You should check out nl2br, which converts the newlines (which won't be visible on a HTML document - as you noticed) to the HTML-tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With