什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
当前回答
我刚刚在输出到Windows客户端时遇到了这个问题。当然,PHP_EOL是针对服务器端的,但是php的大部分内容输出都是针对windows客户端的。所以我必须把我的发现放在这里给下一个人看。
A)呼应“我的短信”。PHP_EOL;//不好,因为这只是输出\n,大多数版本的windows记事本显示在一行上,大多数windows会计软件不能导入这种类型的行结束字符。
B)回复“My Text \r\n”;//不好,因为单引号php字符串不解释\r\n
C)回复“My Text \r\n”;//太棒了!在记事本中看起来正确,并在将文件导入到其他windows软件(如windows会计和windows制造软件)时工作。
其他回答
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太长了,真的不值得使用。
如果要输出多行,使用error_log()非常方便。
在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。
是的,PHP_EOL表面上用于以跨平台兼容的方式查找换行符,因此它处理DOS/Unix问题。
注意,PHP_EOL表示当前系统的结束字符。例如,当在类unix系统上执行时,它将找不到Windows结束行。
当我的PHP没有浏览器时,我使用PHP_EOL常量。实际上,我间接地使用它。查看下面的示例。 例如,有一个叫code的网站。Golf(基本上是堆栈交换代码,但具有交互性)。有一个PHP只有控制台输出,我需要使用PHP_EOL常量来使用这个。
一种缩短它的方法是,一旦你需要使用PHP_EOL常量,就像这样做:
<?php
echo $n = PHP_EOL;
?>
这声明了变量$n,您可以使用它代替PHP_EOL常量作为换行符。甚至比<br>还要短,而且几乎任何需要换行符的东西都可以使用$n !
我发现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";
}
?>