在裸字符串中添加换行符(PHP)

时间:2015-03-17 13:58:15

标签: php text

如果我想从我的网站动态下载包含数据库信息的文本文件,我会使用类似的东西:

$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。)

E.g。

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

2 个答案:

答案 0 :(得分:0)

在字符串中添加\n。但请确保将其添加到双引号中。例如:

echo "Line 1 \n Line 2"

答案 1 :(得分:0)

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);