When do I use the PHP constant "PHP_EOL"? - php

When is it a good idea to use PHP_EOL?
I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

From main/php.h of PHP version 7.1.1 and version 5.6.30:
#ifdef PHP_WIN32
# include "tsrm_win32.h"
# include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
# define PHP_DIR_SEPARATOR '\\'
# define PHP_EOL "\r\n"
#else
# if defined(__GNUC__) && __GNUC__ >= 4
# define PHPAPI __attribute__ ((visibility("default")))
# else
# define PHPAPI
# endif
# define THREAD_LS
# define PHP_DIR_SEPARATOR '/'
# define PHP_EOL "\n"
#endif
As you can see PHP_EOL can be "\r\n" (on Windows servers) or "\n" (on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible for PHP_EOL: "\r" (on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.
As others already told you, you can use PHP_EOL in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.
I just wanted to show the possibles values of PHP_EOL backed by the PHP sources since it hasn't been shown here yet...

You use PHP_EOL when you want a new line, and you want to be cross-platform.
This could be when you are writing files to the filesystem (logs, exports, other).
You could use it if you want your generated HTML to be readable. So you might follow your <br /> with a PHP_EOL.
You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.
You might use it if you are building up an email to send that needed some formatting.

PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
Available since PHP 4.3.10 and PHP 5.0.2
You can use this constant when you read or write text files on the server's filesystem.
Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.
If line endings matter, explicitly specify the line endings instead of using the constant. For example:
HTTP headers must be separated by \r\n
CSV files should use \r\n as row separator

I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.
If outputting to a webpage in HTML, particularly text in <textarea>, <pre> or <code> you probably always want to use \n and not PHP_EOL.
The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).
I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.
As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.
I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.
I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.
For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.
Check out this simple example below:
<?php
$output = 'This is line 1' . PHP_EOL .
'This is line 2' . PHP_EOL .
'This is line 3';
$file = "filename.txt";
if (is_writable($file)) {
// In our example we're opening $file in append mode.
// The file pointer is at the bottom of the file hence
// that's where $output will go when we fwrite() it.
if (!$handle = fopen($file, 'a')) {
echo "Cannot open file ($file)";
exit;
}
// Write $output to our opened file.
if (fwrite($handle, $output) === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
echo "Success, content ($output) wrote to file ($file)";
fclose($handle);
} else {
echo "The file $file is not writable";
}
?>

The definition of PHP_EOL is that it gives you the newline character of the operating system you're working on.
In practice, you should almost never need this. Consider a few cases:
When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway.
If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)
PHP_EOL is so ridiculously long that it's really not worth using it.

There is one obvious place where it might be useful: when you are writing code that predominantly uses single quote strings. Its arguable as to whether:
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
The art of it is to be consistent. The problem with mix and matching '' and "" is that when you get long strings, you don't really want to have to go hunting for what type of quote you used.
As with all things in life, it depends on the context.

I use the PHP_EOL constant in some command line scripts I had to write. I develop on my local Windows machine and then test on a Linux server box. Using the constant meant I didn't have to worry about using the correct line ending for each of the different platforms.

DOS/Windows standard "newline" is CRLF (= \r\n) and not LFCR (\n\r). If we put the latter, it's likely to produce some unexpected (well, in fact, kind of expected! :D) behaviors.
Nowadays almost all (well written) programs accept the UNIX standard LF (\n) for newline code, even mail sender daemons (RFC sets CRLF as newline for headers and message body).

Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.

I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.
Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.

I just experienced this issue when outputting to a Windows client. Sure, PHP_EOL is for server side, but most content output from php is for windows clients. So I have to place my findings here for the next person.
A) echo 'My Text' . PHP_EOL; // Bad because this just outputs \n and most versions of windows notepad display this on a single line, and most windows accounting software can't import this type of end of line character.
B) echo 'My Text \r\n'; //Bad because single quoted php strings do not interpret \r\n
C) echo "My Text \r\n"; // Yay it works! Looks correct in notepad, and works when importing the file to other windows software such as windows accounting and windows manufacturing software.

I am using WebCalendar and found that Mac iCal barfs on importing a generated ics file because the end-of-line is hardcoded in xcal.php as "\r\n". I went in and replaced all occurrences with PHP_EOL and now iCal is happy!
I also tested it on Vista and Outlook was able to import the file as well, even though the end of line character is "\n".

You are writing code that predominantly uses single quote strings.
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";

When jumi (joomla plugin for PHP) compiles your code for some reason it removes all backslashes from your code. Such that something like $csv_output .= "\n"; becomes $csv_output .= "n";
Very annoying bug!
Use PHP_EOL instead to get the result you were after.

On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:
<?php
if (!defined('PHP_EOL')) {
if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
define('PHP_EOL',"\r\n");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
define('PHP_EOL',"\r");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
define('PHP_EOL',"\n");
} else {
define('PHP_EOL',"\n");
}
}
?>
So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...
Note: PHP_EOL can be
1) on Unix LN == \n
2) on Mac CR == \r
3) on Windows CR+LN == \r\n
Hope this answer help.

I use the PHP_EOL constant when I don't have a browser handy with my PHP. Well actually, I use it indirectly. View the example below.
For example, there's this site called code.golf (which is basically stack exchange code golf but interactive). There's a PHP one where there's only console output, and I need to use the PHP_EOL constant to use this.
A way to shorten it is that once you need to use the PHP_EOL constant, just do something like this:
<?php
echo $n = PHP_EOL;
?>
That declares the variable $n, which you can use instead of the PHP_EOL constant as a newline. Even shorter than <br>, and you can use $n for almost anything that needs a newline!

I prefer to use \n\r. Also I am on a windows system and \n works just fine in my experience.
Since PHP_EOL does not work with regular expressions, and these are the most useful way of dealing with text, then I really never used it or needed to.

Related

php problems writing to new line in txt file [duplicate]

What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?
EDIT: In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.
Use the PHP_EOL constant, which is automatically set to the correct line break for the operating system that the PHP script is running on.
Note that this constant is declared since PHP 5.0.2.
<?php
echo "Line 1" . PHP_EOL . "Line 2";
?>
For backwards compatibility:
if (!defined('PHP_EOL')) {
switch (strtoupper(substr(PHP_OS, 0, 3))) {
// Windows
case 'WIN':
define('PHP_EOL', "\r\n");
break;
// Mac
case 'DAR':
define('PHP_EOL', "\r");
break;
// Unix
default:
define('PHP_EOL', "\n");
}
}
\n is a Linux/Unix line break.
\r is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix \n.
\r\n is a Windows line break.
I usually just use \n on our Linux systems and most Windows apps deal with it ok anyway.
Jarod's answer contains the correct usage of \r \n on various OS's. Here's some history:
\r, or the ASCII character with decimal code 13, is named CR after "carriage return".
\n, or the ASCII character with decimal code 10, is named "newline", or LF after "line feed".
The terminology "carriage return" and "line feed" dates back to when teletypes were used instead of terminals with monitor and keyboard. With respect to teletypes or typewriters, "carriage return" meant moving the cursor and returning to the first column of text, while "line feed" meant rotating the roller to get onto the following line. At that time the distinction made sense. Today the combinations \n, \r, \r\n to represent the end of a line of text are completely arbitrary.
No backwards compatibility necessary for PHP_EOL on PHP4.
Need to correct Moore's statement on constant PHP_EOL availability: "... is declared since PHP 5.0.2.".
No, it has been around since PHP 4.3.10. Anyone who is still running anything lesser than that should not be in biz anyhow. As of today no one should be using anything lesser than PHP 5!
From the PHP manual: "PHP_EOL The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2".

Ignoring insert of first new line [duplicate]

When is it a good idea to use PHP_EOL?
I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?
Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.
From main/php.h of PHP version 7.1.1 and version 5.6.30:
#ifdef PHP_WIN32
# include "tsrm_win32.h"
# include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
# define PHP_DIR_SEPARATOR '\\'
# define PHP_EOL "\r\n"
#else
# if defined(__GNUC__) && __GNUC__ >= 4
# define PHPAPI __attribute__ ((visibility("default")))
# else
# define PHPAPI
# endif
# define THREAD_LS
# define PHP_DIR_SEPARATOR '/'
# define PHP_EOL "\n"
#endif
As you can see PHP_EOL can be "\r\n" (on Windows servers) or "\n" (on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible for PHP_EOL: "\r" (on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.
As others already told you, you can use PHP_EOL in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.
I just wanted to show the possibles values of PHP_EOL backed by the PHP sources since it hasn't been shown here yet...
You use PHP_EOL when you want a new line, and you want to be cross-platform.
This could be when you are writing files to the filesystem (logs, exports, other).
You could use it if you want your generated HTML to be readable. So you might follow your <br /> with a PHP_EOL.
You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.
You might use it if you are building up an email to send that needed some formatting.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
Available since PHP 4.3.10 and PHP 5.0.2
You can use this constant when you read or write text files on the server's filesystem.
Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.
If line endings matter, explicitly specify the line endings instead of using the constant. For example:
HTTP headers must be separated by \r\n
CSV files should use \r\n as row separator
I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.
If outputting to a webpage in HTML, particularly text in <textarea>, <pre> or <code> you probably always want to use \n and not PHP_EOL.
The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).
I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.
As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.
I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.
No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.
I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.
I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.
For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.
Check out this simple example below:
<?php
$output = 'This is line 1' . PHP_EOL .
'This is line 2' . PHP_EOL .
'This is line 3';
$file = "filename.txt";
if (is_writable($file)) {
// In our example we're opening $file in append mode.
// The file pointer is at the bottom of the file hence
// that's where $output will go when we fwrite() it.
if (!$handle = fopen($file, 'a')) {
echo "Cannot open file ($file)";
exit;
}
// Write $output to our opened file.
if (fwrite($handle, $output) === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
echo "Success, content ($output) wrote to file ($file)";
fclose($handle);
} else {
echo "The file $file is not writable";
}
?>
The definition of PHP_EOL is that it gives you the newline character of the operating system you're working on.
In practice, you should almost never need this. Consider a few cases:
When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway.
If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)
PHP_EOL is so ridiculously long that it's really not worth using it.
There is one obvious place where it might be useful: when you are writing code that predominantly uses single quote strings. Its arguable as to whether:
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
The art of it is to be consistent. The problem with mix and matching '' and "" is that when you get long strings, you don't really want to have to go hunting for what type of quote you used.
As with all things in life, it depends on the context.
I use the PHP_EOL constant in some command line scripts I had to write. I develop on my local Windows machine and then test on a Linux server box. Using the constant meant I didn't have to worry about using the correct line ending for each of the different platforms.
DOS/Windows standard "newline" is CRLF (= \r\n) and not LFCR (\n\r). If we put the latter, it's likely to produce some unexpected (well, in fact, kind of expected! :D) behaviors.
Nowadays almost all (well written) programs accept the UNIX standard LF (\n) for newline code, even mail sender daemons (RFC sets CRLF as newline for headers and message body).
Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.
I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.
Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.
I just experienced this issue when outputting to a Windows client. Sure, PHP_EOL is for server side, but most content output from php is for windows clients. So I have to place my findings here for the next person.
A) echo 'My Text' . PHP_EOL; // Bad because this just outputs \n and most versions of windows notepad display this on a single line, and most windows accounting software can't import this type of end of line character.
B) echo 'My Text \r\n'; //Bad because single quoted php strings do not interpret \r\n
C) echo "My Text \r\n"; // Yay it works! Looks correct in notepad, and works when importing the file to other windows software such as windows accounting and windows manufacturing software.
I am using WebCalendar and found that Mac iCal barfs on importing a generated ics file because the end-of-line is hardcoded in xcal.php as "\r\n". I went in and replaced all occurrences with PHP_EOL and now iCal is happy!
I also tested it on Vista and Outlook was able to import the file as well, even though the end of line character is "\n".
You are writing code that predominantly uses single quote strings.
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
When jumi (joomla plugin for PHP) compiles your code for some reason it removes all backslashes from your code. Such that something like $csv_output .= "\n"; becomes $csv_output .= "n";
Very annoying bug!
Use PHP_EOL instead to get the result you were after.
On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:
<?php
if (!defined('PHP_EOL')) {
if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
define('PHP_EOL',"\r\n");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
define('PHP_EOL',"\r");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
define('PHP_EOL',"\n");
} else {
define('PHP_EOL',"\n");
}
}
?>
So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...
Note: PHP_EOL can be
1) on Unix LN == \n
2) on Mac CR == \r
3) on Windows CR+LN == \r\n
Hope this answer help.
I use the PHP_EOL constant when I don't have a browser handy with my PHP. Well actually, I use it indirectly. View the example below.
For example, there's this site called code.golf (which is basically stack exchange code golf but interactive). There's a PHP one where there's only console output, and I need to use the PHP_EOL constant to use this.
A way to shorten it is that once you need to use the PHP_EOL constant, just do something like this:
<?php
echo $n = PHP_EOL;
?>
That declares the variable $n, which you can use instead of the PHP_EOL constant as a newline. Even shorter than <br>, and you can use $n for almost anything that needs a newline!
I prefer to use \n\r. Also I am on a windows system and \n works just fine in my experience.
Since PHP_EOL does not work with regular expressions, and these are the most useful way of dealing with text, then I really never used it or needed to.

PHP Line Feeds "\n" Not Saving

For some reason with my code which I'm using \n to break the line, isn't working.
It is outputting without breaking the lines.
$file = "availables.txt";
$current .= $test."\n";
file_put_contents($file, $current);
I'm not sure what's wrong but I read that using single quotes (') doesn't work and I have to use double quotes (") which is what I'm using.
I couldn't really find much but I'm sure this is just a simple issue :)
As alluded to in the comments the issue is in selecting the correct line ending symbol for the platform.
The core constant PHP_EOL will do this for you allowing you to create portable code.
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2
It's true that a line feed character enclosed in single quotes won't work, that's simply because PHP will insert a backspace \ followed by an n into the file. This results in the ASCII/UTF-8 hex code 0x2F0x6E instead of simply 0xA.
Using either "\n" or the predefined constant PHP_EOL which will always contain the correct line feed combination for your platform will resolve this issue.
There's absolutely nothing wrong with the code you posted in your question. So what's wrong? My guess is the program you use to view the resulting file. Some broken Windows applications won't read the line feed correctly because they expect the file to use Windows line feeds (which is a combination of line feed and carriage return as you might know).
You're using PHP, output the file in your browser (no matter which), they'll handle it correctly. Simply:
<?php
header("content-type: text/plain");
echo "hello\nworld";
And you'll see that everything is fine.
You can write you variable inside double quotes like this
$current .= "$test\n";

How to resolve PHP PHP_EOL issue

the constant:
PHP_EOL
is supposed to represent a line break on both windows and linux, however when I run on my linux box there is no spacing (has caused major headaches generating .txt files that now have boxes instead of line breaks).
Any quick fix to the issue?
EDIT
It seems the common answer is that anything created on the Linux machine will not 'appear' correctly within notepad. Is there any to correct this on the back end within notepad itself(a find and replace per say and replace with an actual break?)
Some "fixes":
Use \r\n for your line breaks to make Windows happy.
Don't use notepad.
PHP_EOL only represents something per the system it's running on. It cannot possibly simultaneously represent every EOL sequence that each OS uses.
Don't use PHP_EOL for text-file output.
IIRC it's better to use "\r\n" for best compatibility.
You can DEFINE or $var it if you want.
Use the nl2br() function:
echo nl2br("your first line\n your second line");
You can read text log file to html with line break. This works in Windows and Linux/Unix:
echo str_replace("\n", '<br>', file_get_contents($logfilename));

When do I use PHP_EOL instead of \n and vice-versa ? Ajax/Jquery client problem

I have a php parser that split a given string by line-breaks, doing something like this:
$lines = explode(PHP_EOL,$content);
The parser works fine when working on server side. However, when I pass the content via post by ajax (using jquery's $.post method) the problem arises: line breaks are not recogniezed. So after almost an hour of tests and head-aches I decided to changed PHP_EOL by "\n" and it worked:
$lines = explode("\n",$content);
Now it works! Damn it I lost so much time! Could somebody explain me when use PHP_EOL and "\n" properly, so I can save time in the future? Appreciate your kind answers ;)
The constant PHP_EOL should generally be used for platform-specific output.
Mostly for file output really.
Actually the file functions already transform \n ←→ \r\n on Windows systems unless used in fopen(…, "wb") binary mode.
For file input you should prefer \n however. While most network protocols (HTTP) are supposed to use \r\n, that's not guaranteed.
Therefore it's best to break up on \n and remove any optional \r manually:
$lines = array_map("rtrim", explode("\n", $content));
Or use the file(…, FILE_IGNORE_NEW_LINES) function right away, to leave EOL handling to PHP or auto_detect_line_endings.
A more robust and terser alternative is using preg_split() and a regexp:
$lines = preg_split("/\R/", $content);
The \R placeholder detects any combination of \r + \n. So would be safest, and even work for Classic MacOS ≤ 9 text files (rarely seen in practice).
Obligatory microoptimization note:
While regex has a cost, it's surprisingly often speedier than manual loops and string postprocessing in PHP.
And there are a few classic examples where you should avoid PHP_EOL due to its platform-ambiguity:
Manual generation of network protocol payloads, such as HTTP over fsockopen().
For mail() and MIME construction (which really, you shouldn't do tediously yourself anyway).
File output, if you want to consistently write just Unix \n newlines regardless of environment.
So use a literal "\r\n" combination when not writing to files, but preparing data for a specific context that expects network linebreaks.
PHP_EOL should be used when writing output such as log files.
It will produce the line break specific to your platform.
PHP_EOL is a constant holding the line break character(s) used by the server platform. In the case of Windows, it's \r\n. On *nix, it's \n. You apparently have a Windows server.
If you were on a *nix server, that change wouldn't have fixed it, because it would be \n. If you are sending data to the client (i.e. the browser), you should use \r\n to ensure line breaks are recognized.
PHP_EOL is the line ending used by the server PHP is running on. User submitted content will probably have line ending in whatever format they use. However, instead of exploding on newlines, just using the file() function, it does exactly what you are after.
IMHO using PHP_EOL is preferable
to ensure consistency between PHP and JS handling of line break, you may want to define end-of-line variable in JS using PHP_EOL
var eol = '<?php echo str_replace(array("\n","\r"),array('\\n','\\r'),PHP_EOL) ?>';
afterwards, use eol for splitting submitted textarea content

Categories