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:51

Are you outputting to HTML or plain text? If HTML try adding a <br> at the end of each line. e.g.

while (!feof($handle)) {
  $buffer = fgets($handle, 4096); // Read a line.
  echo "$buffer<br/>";
} 
查看更多
家丑人穷心不美
3楼-- · 2020-01-25 10:53

Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:

<body>
        <div>Some multi-line message below:</div> 
        <div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>

This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.

查看更多
家丑人穷心不美
4楼-- · 2020-01-25 10:58

For simple reads like this, I'd do something like this:

$fileContent = file_get_contents("filename.txt");

echo str_replace("\n","&lt;br&gt;",$fileContent);

This will take care of carriage return and output the text. Unless I'm writing to a file, I don't use fopen and related functions.

Hope this helps.

查看更多
登录 后发表回答