什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
当前回答
我正在使用WebCalendar,发现Mac iCal在导入生成的ics文件时呕吐,因为行尾在xcal.php中硬编码为“\r\n”。我进去,用PHP_EOL替换了所有的事件,现在iCal是快乐的! 我还在Vista和Outlook上进行了测试,即使行尾字符是“\n”,也能导入文件。
其他回答
我在必须编写的一些命令行脚本中使用PHP_EOL常量。我在本地Windows机器上进行开发,然后在Linux服务器上进行测试。使用常量意味着我不必担心为每个不同的平台使用正确的行尾。
您正在编写主要使用单引号字符串的代码。
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
是的,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";
}
?>
如果要输出多行,使用error_log()非常方便。
在我的windows安装中,我发现很多调试语句看起来很奇怪,因为开发人员在拆分字符串时假定unix结尾。