介绍php 常量PHP_EOL的相关知识点

时间:2018-08-09
本文章向大家介绍php 常量PHP_EOL的相关知识点,需要的朋友可以参考一下。

PHP_EOL表面上用于以跨平台兼容的方式查找换行符,因此它处理DOS / Unix问题。

请注意,PHP_EOL表示当前系统的结束字符。例如,在类似unix的系统上执行时,它不会找到Windows端线。

PHP_EOL当您想要一个新行时,您可以使用,并且您希望跨平台。

这可能是在您将文件写入文件系统(日志,导出,其他)时。

如果您希望生成的HTML可读,则可以使用它。所以,你可以按照你的<br />一个PHP_EOL。

如果你从cron运行php作为脚本你需要输出一些东西并将其格式化为屏幕,你会使用它。

如果要构建要发送的电子邮件,则可以使用它,这需要一些格式。

我发现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";
}
?>

从main/php.hPHP版本5.6.30和版本7.1.1:

#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 修复,错误61193。

正如其他人已经告诉过你的那样,你可以PHP_EOL在任何类型的输出中使用(其中任何一个值都是有效的 - 比如:HTML,XML,日志......),你需要统一的换行符(在我看来你应该想要这个)。

我只是想显示PHP_EOLPHP源支持的可能值,因为它还没有在这里显示