如何使用php将字符串作为文件发送到浏览器?

如何使用php将字符串作为文件发送到浏览器?,php,http-headers,Php,Http Headers,我想在内存中创建一个文件,并在单击按钮时将其发送到浏览器。我希望下面的代码能够实现这一点: <?php $content = 'This is supposed to be working... dammit'; $length = strlen($content); header('Content-Description: File Transfer'); header('Content-Type: application/pdf'); header('Content-Disposi

我想在内存中创建一个文件,并在单击按钮时将其发送到浏览器。我希望下面的代码能够实现这一点:

<?php

$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;

?>


相反,我得到了字符串的回声。我愚蠢的新手错误是什么?

你需要更改你的内容类型,这对我来说很有效,在FF和Chrome上测试过

<?php 
$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: text/plain');//<<<<
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;
?>

您需要更改您的内容类型,这对我很有效,在FF和Chrome上进行了测试

<?php 
$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: text/plain');//<<<<
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;
?>


“记住在发送任何实际输出之前必须调用header()”()

“记住在发送任何实际输出之前必须调用header()”()

打开PHP警告。您可能在第一个
header()
之前向浏览器回显了某些内容,在这种情况下,所有的header语句都将被忽略。为什么要输出PDF?我想这完全有可能是你的浏览器启动了你的PDF阅读插件,它看到文本,并呈现它。我尝试了各种内容类型,包括八进制流和PDF。。。也许这与我的apache设置有关……已经有一段时间了,但我也遇到了类似的问题。当您试图下载pdf文件时,文件扩展名为.txt这一事实不会引起任何问题,是吗?打开PHP警告。您可能在第一个
header()
之前向浏览器回显了某些内容,在这种情况下,所有的header语句都将被忽略。为什么要输出PDF?我想这完全有可能是你的浏览器启动了你的PDF阅读插件,它看到文本,并呈现它。我尝试了各种内容类型,包括八进制流和PDF。。。也许这与我的apache设置有关……已经有一段时间了,但我也遇到了类似的问题。当您尝试下载pdf时,文件扩展名为.txt这一事实不会导致任何问题,是吗?如果在调用header()之前发送任何输出,PHP将停止并出错。它不会输出字符串内容。如果在调用header()之前发送了任何输出,PHP将因错误而停止。它不会输出字符串内容。