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


How to send a string as file to the browser using php?

我想在内存中创建一个文件,并在单击按钮时将其发送到浏览器。我期待以下代码可以解决问题:

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

"请记住,在发送任何实际输出之前必须调用 header()" (c)