Output text file with line breaks in PHP

前端 未结 9 1015
一个人的身影
一个人的身影 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 15:02

    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 );
    ?>
    
    0 讨论(0)
  • 2020-11-28 15:09

    One line of code:

     echo nl2br( file_get_contents('file.txt') );
    
    0 讨论(0)
  • 2020-11-28 15:11

    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.

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