什么时候使用php_ol是一个好主意?

我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?


当前回答

我发现PHP_EOL对于文件处理非常有用,特别是在向文件中写入多行内容时。

例如,您有一个很长的字符串,希望在写入普通文件时将其分解成多行。使用\r\n可能行不通,所以简单地将PHP_EOL放入脚本,结果非常棒。

看看下面这个简单的例子:

<?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";
}
?>

其他回答

您正在编写主要使用单引号字符串的代码。

echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;  
echo 'this other $one'."\n";

DOS/Windows标准的换行符是CRLF (= \r\n)而不是LFCR (\n\r)。如果我们选择后者,很可能会产生一些意想不到的结果(好吧,实际上是意料之中的!): D)的行为。

现在,几乎所有(编写良好的)程序都接受UNIX标准LF (\n)作为换行代码,甚至邮件发送守护进程(RFC将CRLF设置为标题和消息正文的换行)。

PHP_EOL的定义是,它为您提供正在操作的操作系统的换行符。

在实践中,您几乎不需要这个。考虑以下几个案例:

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太长了,真的不值得使用。

PHP 7.1.1和5.6.30版本的main/ PHP .h:

#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

正如你所看到的,PHP_EOL可以是“\r\n”(在Windows服务器上)或“\n”(在其他任何服务器上)。在5.4.0RC8之前的PHP版本中,PHP_EOL可能有第三个值:"\r"(在MacOSX服务器上)。这是错误的,已于2012-03-01修复,bug 61193。

正如其他人已经告诉您的那样,您可以在需要统一换行符的任何类型的输出中使用PHP_EOL(这些值中的任何一个都是有效的—例如:HTML、XML、日志……)。请记住,决定值的是服务器,而不是客户机。您的Windows访问者将从您的Unix服务器获取值,这有时对他们来说很不方便。

我只是想展示PHP源代码支持的PHP_EOL的可能值,因为这里还没有显示……

当你想要一个新的行,并且你想跨平台的时候,你可以使用PHP_EOL。

这可能发生在将文件写入文件系统时(日志、导出、其他)。

如果您希望生成的HTML具有可读性,则可以使用它。所以可以在<br />后面加上PHP_EOL。

如果你在cron上运行php脚本,你需要输出一些东西,并将其格式化后显示在屏幕上,你就可以使用它。

如果你要发送一封需要一些格式的电子邮件,你可以使用它。