Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output text file with line breaks in PHP

I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?

Thanks.

<html>

<head>

</head>

<body>

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

        $pageText = fread($fh, 25000);

        echo $pageText;


</body>

</html>
like image 809
usertest Avatar asked Jan 13 '10 19:01

usertest


People also ask

How do you add a line break in PHP?

Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

Can we use \n in PHP?

?> Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.


1 Answers

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.

like image 100
MattBelanger Avatar answered Oct 07 '22 00:10

MattBelanger