Output text file with line breaks in PHP

2020-01-25 10:30发布

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>

9条回答
走好不送
2楼-- · 2020-01-25 10:33

Trying to get line breaks to work reading a .txt file on Apache2 and PHP 5.3.3 with MacOSX 10.6.6 and Camino, the echo nl2br( $text); didn't work right until I printed the file size first too. BTW it doesn't seem to matter if the .txt file has Linux/MacOSX LF or Windows CRLF line breaks or the text encoding is UTF-8 or Windows Latin1, Camino gets it out OK.

<?php
$filename     = "/Users/Shared/Copies/refrain.txt";
$file_ptr     = fopen ( $filename, "r" );
$file_size    = filesize ( $filename );
$text         = fread ( $file_ptr, $file_size );
fclose ( $file_ptr );
echo ( "File size : $file_size bytes<br>&nbsp;<br>" );
echo nl2br ( $text );
?>
查看更多
淡お忘
3楼-- · 2020-01-25 10:36

Before the echo, be sure to include

header('Content-Type: text/plain');
查看更多
Anthone
4楼-- · 2020-01-25 10:39

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.

查看更多
成全新的幸福
5楼-- · 2020-01-25 10:39

You need to wrap your PHP code into <?php <YOU CODE HERE >?>, and save it as .php or .php5 (depends on your apache set up).

查看更多
冷血范
6楼-- · 2020-01-25 10:43

One line of code:

 echo nl2br( file_get_contents('file.txt') );
查看更多
你好瞎i
7楼-- · 2020-01-25 10:46

If you just want to show the output of the file within the html code formatted the same way it is in the text file you can wrap your echo statement with a pair of pre tags:

echo "<pre>";
echo $pageText;
echo "</pre>";

Some of the other answers look promising depending on what you are trying todo.

查看更多
登录 后发表回答