无法通过 txt 文件中的新行分解字符串

cannot explode a string by new lines from a txt file

无法通过 txt 文件中的新行分解字符串

colors.txt

rgb(15, 255, 255)
rgb(15, 255, 252)
rgb(15, 255, 249)

php

$str = file_get_contents('colors.txt');
$arr = explode(PHP_EOL, $str);
$ht = '';
foreach($arr as $el){
    $ht .= "<div class='color' style='background:" . $el . "'></div>\n";
}
echo $ht; // nothing visible on page

也试过

$arr = explode('\n', $str);
$arr = explode('\n\r', $str);
$arr = explode('\r\n', $str);
$arr = explode('LF', $str); // LF stands in notepad++

有什么帮助吗?

尝试使用这个:

preg_split('/\r\n|\r|\n/', $str);

使用file()函数:

$str = file('colors.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$ht = '';
foreach($str as $el){
    $ht .= "<div class='color' style='background:" . $el . "'></div>\n";
}
echo $ht;

如果您正确输出文件,我认为这是重复的。

EOL 是系统特定的,如果文件未在系统 运行 PHP 上正确创建,它将无法工作。

您可以在这里查看正确答案: