What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We’ll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an end-of-line character. It helps in dealing with text file I/O operations in PHP.

Linux and macOS represent the end-of-line marker by the newline character (\n), whereas Windows environments are represented by a combination of two characters a newline (\r\n).

Also checkout other related tutorials,

Merge Two Array or Multiple Array in PHP
How To Convert XML To Associative Array in PHP
Remove Duplicates From Multidimensional Array
How To Convert XSD into Array Using PHP

There are the following end-line characters used by the platform:

  • Unix-based systems (e.g., Linux, macOS) typically use the newline character (\n) to represent the end of a line.
  • Windows uses a combination of newline (\r\n) sequence.
  • Classic Mac OS (pre-OS X) historically used only the carriage return (\r) character.

Writing to Files:

Let’s write a file that has two dummy lines and will use PHP_EOL, The PHP_EOL will add end-of-line marker based on the Operating system where the script is running.

$file = fopen('phpflow.txt', 'w');
fwrite($file, 'Line 1' . PHP_EOL);
fwrite($file, 'Line 2' . PHP_EOL);
fclose($file);

The above code will write two lines of text to a file named 'phpflow.txt'.

Concatenating Strings

We can also use PHP_EOL constant to concatenate ‘Hello’ and ‘World’ with the appropriate line break between them.

$message = 'Hello' . PHP_EOL . 'World';
echo $message;

PHP_EOL with Heredoc or Nowdoc Syntax:

We can also use php_eol constant with heredoc and newdoc.

$text = <<<EOT
This is a multiline string.
It spans multiple lines.
And ends here.
EOT;
echo $text . PHP_EOL;

Conclusion

We have discussed different scenarios to apply PHP_EOL with PHP application. You can add an end-line marker into your string into a text regardless of platform. You can create strings/file by using php_eol and it’ll apply end-of-line characters based on PHP platform environment. It helps to write cross-platform code that helps end-of-line endings.

Leave a Reply

Your email address will not be published. Required fields are marked *