将字符串写入文件并在PHP中强制下载


Writing string to file and force download in PHP

我正在研究如何从字符串创建文件的方法,这可能是纯文本,保存为.txt和php等,但我希望能深入了解

**我发现这个代码

$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith'n";
// Write the contents back to the file
file_put_contents($file, $current);

但是我需要在我的服务器上保存people.txt吗?

强制下载部分

header("Content-Disposition: attachment; filename='"" . basename($File) . "'"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($File));
header("Connection: close");

我需要把上面的东西放在哪里,我假设代码是正确的,可以强制下载我现成的文件?

您不需要将字符串写入文件即可将其发送到浏览器。请参阅以下示例,它将提示UA尝试下载一个名为"sample.txt"的文件,该文件包含$str:的值

<?php
$str = "Some pseudo-random
text spanning
multiple lines";
header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($str));
header('Connection: close');

echo $str;