Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to convert plain text into HTML with line breaks?

Tags:

php

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.)

like image 390
Chrispy Avatar asked Feb 19 '12 00:02

Chrispy


2 Answers

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);
like image 185
Vyktor Avatar answered Sep 27 '22 20:09

Vyktor


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

like image 25
Zar Avatar answered Sep 27 '22 20:09

Zar