0

I have read the thread Writing a new line to file in PHP pasted the exact code of there in my own netbeans IDE but didn't work. The pasted code (with some minor changes) was:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
$i = 0;
$file = fopen('ids.txt', 'w');
$gemList=array(1,2,3,4,5);
foreach ($gemList as $gem)
{
    fwrite($file, $gem."\n");
    $i++;
}
fclose($file);        
?>
    </body>
</html>

I also tried to write in a new line of file using another code. My code goes like this:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        $fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>
    </body>
</html>

but the result in the text file is

12345

and what I expect is

1

2

3

4

5

I greatly appreciate any help. Also my Netbeans version is 8.2 and my running OS is Windows 10.

Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16

3 Answers3

5

With your current code, check the page source and it is giving you the correct result.

But remember that you are running it on an html page so if you want a new line, use the <br> tag.

foreach ($gemList as $gem)
{
    fwrite($file, $gem."<br>");
    $i++;
}
fclose($file);  

HTML does not take new lines \n into consideration, unless you specifically set the CSS property white-space:pre;

Ibu
  • 42,752
  • 13
  • 76
  • 103
0

Ibu's answer is correct if you are displaying on a webpage.

For your fwrite() call, be sure the text viewer you are using understands \n as the EOL character. In other words if you are on Windows, and will only work with the resulting file(s) on Windows, a \n\r (new line and carriage return) is what you want to use for your EOL character(s)

Or, leave as-is, and use a text editor that supports "Unix style line endings" - Notepad++ does...

ivanivan
  • 2,155
  • 2
  • 10
  • 11
0

If you are viewing the content of your file in the browser (eg. echoed in PHP) you need to use the nl2br() PHP function to convert newlines to html's <br/>:

<div>
<?= nl2br(file_get_contents("testfile.txt")); ?>
</div>

Alternatively enclose the file content withing a with CSS white-space property set to "pre":

<div style="white-space: pre">
<?= file_get_contents("testfile.txt"); ?>
</div>
maxidirienzo
  • 99
  • 1
  • 6