PHP New Line will not work

戏子无情 提交于 2019-11-26 22:07:35

问题


Hi I am trying to create some code that first reads the existing contents of the file in and then adds the new line of code on a new line but the code i am using just adds it on the new text on to the already existing line instead of the new line...

Here is the code i am using:

<?php

$id = $_GET['id'];

$userfile = "user1.txt";
$fo = fopen($userfile, 'r') or die("can't open favourites file");
$currentdata = fread($fo, filesize($userfile));
fclose($fo);
$fw = fopen($userfile, 'w') or die("can't open favourites file");
$currentprocessed = "$currentdata\n";
fwrite($fw, $currentprocessed);
fwrite($fw, $id);
fclose($fw);
?>

I have tried a whole range of different ideas but nothing has worked, any help would be appreciated.


回答1:


Instead of appending \n, concatenate the constant PHP_EOL which is always the correct newline character for the current platform.

It might also be an issue with the program you're using to open the text file with. For instance, Notepad on Windows is incapable of understanding unix style newlines.




回答2:


Line endings per OS

Unix / Linux
\n

DOS / Windows
\r\n

Invalid
\r and \n\r


The value of PHP_EOL constant depends on the platform php is running on.
It doesn't detect the line-endings in the current file or anything magic.




回答3:


I ran into this same issue. What application are you using to read the file? I found that for some reason Notepad (my default for .txt files) didn't recognize the "\n\r" escape characters. I opened my .txt file that I was writing to using Notepad++, Atom (my text editor of choice), or in a browser and they all showed the line breaks just fine.



来源:https://stackoverflow.com/questions/3031597/php-new-line-will-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!