什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
什么时候使用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";
}
?>
其他回答
如果要输出多行,使用error_log()非常方便。
在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。
当jumi (joomla plugin for PHP)出于某种原因编译你的代码时,它会从你的代码中删除所有的反斜杠。例如$csv_output .= "\n";$csv_output .= "n";
非常讨厌的虫子!
使用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不处理端点问题,因为使用该常量的系统与将输出发送到的系统不同。
我完全不建议使用PHP_EOL。Unix/Linux使用\n, MacOS / OS X也从\r改为\n,在Windows上,许多应用程序(特别是浏览器)也可以正确显示它。在Windows上,更改现有的客户端代码仅使用\n并保持向后兼容性也很容易:只需将行切边的分隔符从\r\n更改为\n,并将其包装在类似trim()的函数中。
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太长了,真的不值得使用。