什么时候使用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";
}
?>
其他回答
当jumi (joomla plugin for PHP)出于某种原因编译你的代码时,它会从你的代码中删除所有的反斜杠。例如$csv_output .= "\n";$csv_output .= "n";
非常讨厌的虫子!
使用PHP_EOL来获得您想要的结果。
是的,PHP_EOL表面上用于以跨平台兼容的方式查找换行符,因此它处理DOS/Unix问题。
注意,PHP_EOL表示当前系统的结束字符。例如,当在类unix系统上执行时,它将找不到Windows结束行。
我发现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";
}
?>
DOS/Windows标准的换行符是CRLF (= \r\n)而不是LFCR (\n\r)。如果我们选择后者,很可能会产生一些意想不到的结果(好吧,实际上是意料之中的!): D)的行为。
现在,几乎所有(编写良好的)程序都接受UNIX标准LF (\n)作为换行代码,甚至邮件发送守护进程(RFC将CRLF设置为标题和消息正文的换行)。
我有一个站点,其中一个日志脚本在用户的操作之后向文本文件写入新一行文本,用户可以使用任何操作系统。
在这种情况下,使用PHP_EOL似乎不是最优的。如果用户是在Mac OS上,并写入文本文件,它将放置\n。当在windows计算机上打开文本文件时,它不会显示换行符。因此,我使用“\r\n”来代替在任何操作系统上打开文件时的工作。