4

I want to save result for looping with enter with this code

$str = '';
for( $i = 1; $i <= 10; $i++ ) {
    $str .= $i;    
}

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = $str . "\n";
fwrite($myfile, $txt);
fclose($myfile);

but the result is

12345678910

I want the result is like

1
2
3
4
5
6
7
8
9
10

then I try to use this script

$str = '';
for( $i = 1; $i <= 10; $i++ ) {
    $str .= $i . "<br>";    
}

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = $str . "\n";
fwrite($myfile, $txt);
fclose($myfile);

the result like

1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>

anyone can help me to fix this script please ?

George G
  • 7,443
  • 12
  • 45
  • 59
Fian Julio
  • 39
  • 6

4 Answers4

3

You may want to simply add the new-line directly within the Loop to get what you want like this:

    <?php
        $str = '';
        for( $i = 1; $i <= 10; $i++ ) {
            $str .= $i . PHP_EOL;   //<== ADD A NEW LINE AT THE END OF EACH DIGIT 
        }

        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
        //$txt  = $str . "\n";  //<== YOU WOULDN'T NEED THIS LINE ANYMORE
        fwrite($myfile, $str);
        fclose($myfile);
Poiz
  • 7,611
  • 2
  • 15
  • 17
2

you have to use a new line in such a way

try:

$txt = $str.PHP_EOL;
bradley546994
  • 630
  • 2
  • 12
  • 30
1

Try adding a \r

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = $str . "\r\n";
fwrite($myfile, $txt);
fclose($myfile);
Rafael Shkembi
  • 786
  • 6
  • 16
0

You save only a var with 12345678910 in your file. If you save every line with a wordwrap it should work. Like this:

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

for( $i = 1; $i <= 10; $i++ ) {
    fwrite($myfile, $i . "\n";);  
}

fclose($myfile);