我想用enter保存结果以进行循环

时间:2016-07-15 07:39:51

标签: php

我想保存结果以使用此代码输入

进行循环
$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);

但结果是

12345678910

我想结果就像

1
2
3
4
5
6
7
8
9
10

然后我尝试使用这个脚本

$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);

结果如

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

任何人都可以帮我修复这个脚本吗?

4 个答案:

答案 0 :(得分:3)

您可能只想在循环中直接添加换行符以获得您想要的内容:

    <?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);

答案 1 :(得分:2)

你必须以这种方式使用新行

尝试:

dotnet pack

答案 2 :(得分:1)

尝试添加\ r

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

答案 3 :(得分:0)

您只能在文件中保存带有12345678910的var。如果你用wordwrap保存每一行它应该工作。像这样:

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

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

fclose($myfile);