无法在文本文件中创建换行符

时间:2014-03-22 04:32:38

标签: php

我在txt文件中写入数据。但是,写入数据无法创建新行。这是我的代码

<?php
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$fh=fopen("address.txt","a");
for($i=0;$i<3;$i++)
{
    fwrite($fh,$address[$i]."\n");
}
fclose($fh);
?>

写入数据在txt文件中看起来像这样

jon smith,1234 oak st.,big city,or, 9999jon smith,1234 oak st.,big city,or, 9999jon smith,1234 oak st.,big city,or, 9999

我在fwrite结束时尝试了#34; \n",但它似乎无法正常工作。

3 个答案:

答案 0 :(得分:3)

您正在为新行使用\n字符,这对于基于* nix的系统是正确的。在Windows中它是\r\n。在其他平台上可能会有所不同。请改用PHP_EOL。这将正确添加当前平台的换行符。

您查看文件时使用的编辑器也可能存在问题。例如,记事本只会将\r\n识别为换行符。在这种情况下,您使用\n,因此如果您使用记事本,则不会显示这些内容。解决方案是使用记事本可识别的正确序列,或者完全使用不同的编辑器(Notepad ++很好)。

答案 1 :(得分:1)

试试这个:

这是最简单的方法。

<?php
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$fh=fopen("address.txt","a");
for($i=0;$i<3;$i++)
{
    fwrite($fh,$address[$i]."
");
}
fclose($fh);
?>

但您也可以将\r\n用于新行甚至是PHP_EOL

答案 2 :(得分:1)

尝试PHP_EOL这里是代码

<?php
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$address[] = "jon smith,1234 oak st.,big city,or, 9999";
$fh=fopen("address.txt","a");
for($i=0;$i<3;$i++)
{
    fwrite($fh,$address[$i].PHP_EOL);
}
fclose($fh);
?>

和输出

jon smith,1234 oak st.,big city,or, 9999
jon smith,1234 oak st.,big city,or, 9999
jon smith,1234 oak st.,big city,or, 9999