【问题标题】:Empty top line spacing in the text file文本文件中的空顶行间距
【发布时间】:2016-01-28 17:54:11
【问题描述】:

我正在尝试通过 Kohana 框架生成和下载一个文本文件,但它为以内容开头的第二行添加了一个空的顶行和制表符缩进。这是我的代码:

<?php
class Controller_Add extends Controller_Siteadmin 
{
    public function __construct(Request $request, Response $response)
    {
        parent::__construct($request, $response);   
    }
    public function action_sample()
    {
        $content ="hello this is sample text file";
        $filename = "yourfile.txt";
        $f = fopen($filename, 'w');
        fwrite($f, $content);
        fclose($f);
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Length: ". filesize("$filename").";");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/octet-stream; "); 
        header("Content-Transfer-Encoding: binary");
        readfile($filename);
    }
}
?>

还有输出:

如果我创建一个专用的 PHP 文件,问题就不存在了,只有当我使用 Kohana 框架 3.2.2 进行尝试时才会出现问题。

仅供参考:我什至删除了 index.php、database.php 和 bootstrap.php 中的所有间距

我需要的是没有空的顶行和第二行缩进,有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你试过Content-Type: text/plain吗?
  • 刚刚做了,但没有运气。
  • ?&gt; 结束标记之后或&lt;?php 开始标记之前是否有空格?任何制表符或换行符都将包含在生成的输出中。
  • 我确实尝试了将 ?> 关闭和删除的两种情况,但没有区别。在顶部,我也做了一些测试,删除了所有空格。
  • 会不会是包含的库(Kohana)里有这样的空白?

标签: php text download kohana fwrite


【解决方案1】:

为此,Kohana 在Response 对象中有send_file 方法。

此方法可从Controller 对象的$this-&gt;response 属性获得,例如:

$this->response->send_file();

您可以将生成的内容下载为文本文件,您可以在Controller 中使用以下代码:

$this->response
    ->body('hello this is sample text file')
    ->send_file(true, 'yourfile.txt');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多