什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
当前回答
当jumi (joomla plugin for PHP)出于某种原因编译你的代码时,它会从你的代码中删除所有的反斜杠。例如$csv_output .= "\n";$csv_output .= "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";
}
?>
如果要输出多行,使用error_log()非常方便。
在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。
有一个明显的地方它可能有用:当您编写主要使用单引号字符串的代码时。有争议的是:
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
它的艺术在于始终如一。混合和匹配"和"的问题是,当你得到很长的字符串时,你真的不想去寻找你使用的引用类型。
就像生活中的所有事情一样,这取决于上下文。
我在必须编写的一些命令行脚本中使用PHP_EOL常量。我在本地Windows机器上进行开发,然后在Linux服务器上进行测试。使用常量意味着我不必担心为每个不同的平台使用正确的行尾。
在某些系统上,使用这个常量可能是有用的,因为如果,例如,您正在发送电子邮件,您可以使用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
希望这个答案能有所帮助。