Skip to content
PHP Logo

How can PHP handle line breaks in different operating systems when writing to a file?

When writing to a file in PHP, line breaks may be handled differently on different operating systems (e.g., Windows, Unix, macOS). To ensure consistent line breaks, you can use the PHP_EOL constant, which represents the correct end-of-line character for the current platform. By using PHP_EOL instead of manually inserting line breaks, your code will automatically adapt to the correct line break style for the operating system it is running on.

php
<?php
$file = 'example.txt';
$data = "Hello, world!" . PHP_EOL;

file_put_contents($file, $data, FILE_APPEND);
?>