Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a new line to file in PHP (line feed)

People also ask

How do I create a new line in Fwrite PHP?

When writing to a file in PHP with fwrite , you can add a newline character with PHP_EOL. Using PHP_EOL instead of manually writing out a "\n" or "\r\n" is important to make your code as portable as possible.

How do you declare a new line?

With early computers, an ASCII code was created to represent a new line because all text was on one line. In programming languages, such as C, Java, and Perl, the newline character is represented as a '\n' which is an escape sequence.

Does BR work in PHP?

Using Line Breaks as in HTML: The <br> tag in HTML is used to give the single line break. It is an empty tag, so it does not contain an end tag. Example: PHP.

What is the use of \r in PHP?

\r is a Carriage Return \n is a Line Feed (or new line). On Windows systems these together make a newline (i.e. every time you press the enter button your fix will get a \r\n ). In PHP if you open a Windows style text file you will get \r\n at the end of paragraphs / lines were you've hit enter.


Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").


Use PHP_EOL which outputs \r\n or \n depending on the OS.


PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);