Output text file with line breaks in PHP

前端 未结 9 1014
一个人的身影
一个人的身影 2020-11-28 14:11

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?<

相关标签:
9条回答
  • 2020-11-28 14:48

    Before the echo, be sure to include

    header('Content-Type: text/plain');
    
    0 讨论(0)
  • 2020-11-28 14:49

    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.

    0 讨论(0)
  • 2020-11-28 14:49

    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/>";
    } 
    
    0 讨论(0)
  • 2020-11-28 14:49

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

    0 讨论(0)
  • 2020-11-28 14:58

    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>" . $pageText . "</pre>;
    

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

    0 讨论(0)
  • 2020-11-28 14:59

    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.

    0 讨论(0)
提交回复
热议问题