【问题标题】:Adding line breaks to a bare string (PHP)将换行符添加到裸字符串 (PHP)
【发布时间】:2015-03-17 13:58:14
【问题描述】:

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

$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

【问题讨论】:

  • 什么是大空间?多个空格、制表符等?

标签: php text


【解决方案1】:

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

echo "Line 1 \n Line 2"

【讨论】:

    【解决方案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);
    

    【讨论】:

    • 不,这是我在代码中进一步定义的函数。它使用准备好的语句从数据库中获取数据。
    猜你喜欢
    • 2015-10-21
    • 2019-07-13
    • 2012-01-22
    • 2015-10-22
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多