Writing a New Line to File in PHP (Line Feed)
This issue arises when using fwrite with 'n' to write a new line to a file, and instead of creating a new line, it prints 'n' as a string in the file.
To resolve this, simply replace 'n' with "n". The escape sequence is not recognized when using ' (single quotes). This is because ' (single quotes) are used for unescaped strings, and 'n' is treated as a string literal representing the characters n.
For example, consider this code:
$file = fopen('ids.txt', 'w'); fwrite($file, $gem->getAttribute('id') . "\n");
In this code, "n" is used as the new line character, ensuring that a new line is created in the file.
Regarding the use of rn (carriage return and new line), it is typically used on Windows systems to represent a new line. However, if you want to write line endings consistently across operating systems, you should adopt a single convention, such as using "n" for all operating systems. Additionally, it is recommended to open your file in binary mode (e.g., using 'wb'), as this ensures that line endings are written correctly when transferring files between systems with different conventions.
The above is the detailed content of Why does `fwrite` not create a new line when using `\n` in PHP?. For more information, please follow other related articles on the PHP Chinese website!