Search code examples
phpfile-get-contents

how to read a txt file with spaces and line breaks into it


I have a flatfile database-001.txt file in which entries. My txt file looks like this:

Bill

message Bill goes here
1571436403

==
John

message John goes here
1571436126

==
Earl

message earl goes here 
1571436051

==


For reading the .txt file, i use this code:

$flatfile = file_get_contents('database-001.txt');
echo $flatfile;
?>

But using it like this, it generates this:

Bill message Bill goes here 1571436403==Johnmessage John goes here1571436126==Earlmessage earl goeshere 1571436051==

How can i read the content with the line breaks and white lines in it exactly as in the .txt file?


Solution

  • Try:

    $flatfile = file_get_contents('database-001.txt');
    echo nl2br($flatfile);
    

    What is happening is, the browser doesn't understand \n. You should use <br> instead. nl2br transforms all classic new lines \n to <br>.

    You can easily see this with the following example:

    $str1 = "regular \n newline";
    $str2 = "browser <br> newline";
    echo str1;
    echo str2;