向裸字符串 (PHP) 添加换行符


Adding line breaks to a bare string (PHP)

假设如果我想从我的网站动态下载一个包含数据库信息的文本文件,我会使用如下内容:

$name = $_GET["download"];
$file = get_file_data($name);
if ($file) {
    header("Content-Disposition: attachment; filename=".$file["custom_name"].".txt");
    header("Content-Type: text/plain");
    echo $file["stuff"];
    exit();
}

其中$file["stuff"]是直接从数据库中读取的裸文本字符串。

但是,存储的文本中似乎没有任何明确的换行符,相反,当显示裸露时,它们看起来像段落块之间的大空格。

(当然,当显示在HTML页面上的pre标签中时,换行符就在那里,因为大多数现代浏览器中pre的CSS。

例如

The Last Question by Isaac Asimov © 1956          The last question was asked for the first time, half in jest, on May 21, 2061, at a time when humanity first stepped into the light. The question came about as a result of a five dollar bet over highballs, and it happened this way:

如何遍历任何这样的字符串并在每行末尾强制执行PHP_EOL

向字符串添加一个'n。但请确保它以双引号添加。例:

echo "Line 1 'n Line 2"

get_file_data是一个wordpress函数,所以我不确定这是否是你想要的。

$name = $_GET["download"];
 //... sanitize the input first.
$thetext = file_get_contents($name); 
if($thetext)
header("Content-Disposition: attachment; filename='"" . basename($filename) . "'"");
echo nl2br($thetext);