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

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


当前回答

如果要输出多行,使用error_log()非常方便。

在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。

其他回答

如果要输出多行,使用error_log()非常方便。

在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。

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

我更喜欢用\n\r。而且我在windows系统上,\n在我的经验中工作得很好。

由于PHP_EOL不能与正则表达式一起工作,而正则表达式是处理文本的最有用的方法,所以我真的从未使用过它,也不需要使用它。

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

在某些系统上,使用这个常量可能是有用的,因为如果,例如,您正在发送电子邮件,您可以使用PHP_EOL让跨系统脚本在更多系统上工作…但即使它是有用的,有时你会发现这个常数未定义,现代主机与最新的php引擎没有这个问题,但我认为一件好事是写一些代码来挽救这种情况:

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

所以你可以毫无问题地使用php_ol…很明显,PHP_EOL应该在脚本上使用,应该在多个系统上同时工作,否则你可以使用\n或\r或\r\n…

备注:PHP_EOL可以为

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

希望这个答案能有所帮助。