I want to save the result for a loop with enter

I want to save the result for a loop with enter using 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

12345678910

I want the result to be like

1
2
3
4
5
6
7
8
9
10

then i am trying 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);

similar result

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

can anyone help me fix this script please?

+4
source share
4 answers

You can simply add a new line directly in Loop to get what you want:

    <?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);
+3
source

you need to use a new line this way

to try:

$txt = $str.PHP_EOL;
+2
source

\r

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

var 12345678910 . wordwrap, . :

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

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

fclose($myfile);
0

Source: https://habr.com/ru/post/1647989/


All Articles