php继续使用新的换行符写入文件

时间:2012-09-24 07:07:14

标签: php file

如何在每次执行将数据写入文本文件后中断新行?

该文件显示没有新换行符的记录:

  

countryId:20,productId:332,status:1,opId:188,xId:pdgje9876,countryId:20,productId:334,status:0,opId:188,xId:pfgje3455,

这是我需要的输出:

  

countryId:20,productId:332,status:1,opId:188,xId:pdgje9876,

     

countryId:20,productId:334,status:0,opId:188,xId:pfgje3455,

$txt = "log.txt";
$fh = fopen($txt, 'a') or die("can't open file");

foreach($obj as $key => $value) {
    print "$key => $value<br>";

    $stringData = $key.":".$value.", ";
    fwrite($fh, $stringData);

}
fclose($fh);

2 个答案:

答案 0 :(得分:2)

在每一行结束时添加"\n"

$txt = "log.txt";
$fh = fopen($txt, 'a') or die("can't open file");

foreach ($objects as $obj) {
  foreach($obj as $key => $value) {
    print "$key => $value<br>";

    $stringData = $key.":".$value.", ";
    fwrite($fh, $stringData);
  }
  fwrite($fh, "\n");
}
fclose($fh);

答案 1 :(得分:0)

您可能希望在行尾添加“\ n”。

$txt = "log.txt";
$fh = fopen($txt, 'a') or die("can't open file");

foreach($obj as $key => $value) {
    print "$key => $value<br>";
    if ($key == "xld") {
        $stringData = $key.":".$value.",\n"; // Will add new line after xld key
    } else {
        $stringData = $key.":".$value.", ";
    }
    fwrite($fh, $stringData);

}
fclose($fh);