用PHP写入文件时fwrite()函数无法使内容换行问题的解决方案(多种方案,一定要看到最后)

在PHP and MySQL Web Development这本书中49页,在写入文件的时候用到了函数fwrite()

$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
                      .$sparkqty." spark plugs\t\$".$totalamount
                      ."\t". $address."\n";//注意这里的\n 根本没起作用

fwrite($fp, $outputstring, strlen($outputstring));

无论是这个函数还是,其参数 $outputstring,均无法满足使得文件追加内容得到换行。

如果纯粹如上面这种格式写入processorder_2.php文件,结果如下:

因此并没有换行,那么我的解决办法如下:

首先百度了经验,地址:http://www.shuchengxian.com/article/575.html

那么我的解决办法是在关闭文件函数的前面或者后面加一个函数:

flock($fp, LOCK_UN);
       fwrite($fp, $outputstring, strlen($outputstring));
       flock($fp, LOCK_UN);//LOCK_UN
       fclose($fp);
       file_put_contents("$document_root/../orders/orders.txt", PHP_EOL, FILE_APPEND);//关闭后

或者:

flock($fp, LOCK_UN);
       fwrite($fp, $outputstring, strlen($outputstring));
       flock($fp, LOCK_UN);//LOCK_UN
       file_put_contents("$document_root/../orders/orders.txt", PHP_EOL, FILE_APPEND);//关闭前
       fclose($fp); 

或者:

flock($fp, LOCK_UN);
       fwrite($fp, $outputstring, strlen($outputstring));
       file_put_contents("$document_root/../orders/orders.txt", PHP_EOL, FILE_APPEND);
       flock($fp, LOCK_UN);//LOCK_UN
       fclose($fp);

 以上答案均正确!对于这个函数的插入位置,只要是这个整体之间都行。并且最后文件内容添加格式都如下图所

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值