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

My code is:

$i = 0; $file = fopen('ids.txt', 'w'); foreach ($gemList as $gem) { fwrite($file, $gem->getAttribute('id') . '\n'); $gemIDs[$i] = $gem->getAttribute('id'); $i++; } fclose($file); 

For some reason, it writes \n as a string, so the file looks like this:

 40119\n40122\n40120\n42155\n36925\n45881\n42145\n45880 

At Google, he tells me to use \r\n , but \r is a carriage return, which doesn't seem to be what I want to do. I just want the file to look like this:

 40119 40122 40120 42155 36925 45881 42145 45880 

Thank.

+94
file php newline fopen linefeed fwrite
Jun 18 '10 at 0:00
source share
4 answers

Replace '\n' with "\n" . After using the ' escape sequence is not recognized.

See manual .

For a question on how to write line endings, see the note here . In principle, different operating systems have different conventions for line endings. Windows uses "\ r \ n", UNIX-based operating systems use "\ n". You must adhere to one convention (I chose "\ n") and open the file in binary mode ( fopen should get "wb", not "w").

+243
Jun 18 '10 at 0:00
source share

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

+59
Sep 16 '11 at 19:58
source share

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

Using this, you will save additional coding in cross-platform development.

IE

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

If you loop this twice, you will see in "somefile":

 some data some data 
+55
Feb 17 '13 at 21:29
source share

You can also use file_put_contents() :

 file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND); 
+21
Jun 18 2018-10-18T00:
source share



All Articles