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

ngp*_*und 4 php

我正在研究如何从字符串创建文件的方法,这可能是纯文本将保存为.txt和PHP为.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);
Run Code Online (Sandbox Code Playgroud)

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

力下载部分

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($File));
header("Connection: close");
Run Code Online (Sandbox Code Playgroud)

我需要在哪里容纳上述内容,我假设代码是强制下载我的现成文件的权利?

TML*_*TML 25

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

<?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;
Run Code Online (Sandbox Code Playgroud)