问题
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?
回答1:
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.
回答2:
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...
回答3:
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.
回答4:
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
回答5:
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.
回答6:
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.
回答7:
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";
}
?>
回答8:
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.
回答9:
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.
回答10:
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).
回答11:
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.
回答12:
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.
回答13:
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";
回答14:
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.
回答15:
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".
回答16:
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.
回答17:
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.
回答18:
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.
回答19:
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.
来源:https://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol