简体   繁体   English

如何为TWIG呈现的页面返回Content-Length标头?

[英]How to return Content-Length header for TWIG rendered page?

I am rendering a TWIG template to generate a CSV file to download. 我正在渲染TWIG模板以生成CSV文件进行下载。 In order to show a progress bar for the download, the server must return the Content-Length header. 为了显示下载的进度条,服务器必须返回Content-Length标头。

I tried rendering the TWIG template into a variable, calculating the length of this string, then outputting the content-length header immediately before echo'ing the rendered template: 我尝试将TWIG模板呈现为一个变量,计算该字符串的长度,然后在回显呈现的模板之前立即输出content-length标头:

$output = $twig->render(...);
header('Content-Length', strlen($output));
echo $output;

But this throws a server 500 error with the message "malformed header from script 'index.php': Bad header: Content-Length". 但这会引发服务器500错误,并显示消息“脚本'index.php'的标头格式错误:标头错误:Content-Length”。

Am I missing something here? 我在这里想念什么吗? Seems this should be trivial. 看来这应该是微不足道的。

The first parameter passed to header() should be the complete header string. 传递给header()的第一个参数应该是完整的标题字符串。 I guess you expected header function to accept the first and second parameters like header(field name,field value) , but that's not the case. 我猜您希望标头函数接受header(field name,field value)类的第一个和第二个参数,但事实并非如此。 You should headers as a single string like this: 您应该将标头作为单个字符串,如下所示:

// something like 'Content length: 1234'
header('Content-Length: ' . strlen($output));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM