5

我正在研究如何从字符串创建文件的方法,这可能是纯文本将另存为 .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);

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

强制下载部分

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

我需要在哪里存放上述内容,我假设代码是正确的,可以强制下载我的现成文件?

4

1 回答 1

30

您无需将字符串写入文件即可将其发送到浏览器。请参阅以下示例,它将提示您的 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;
于 2013-02-25T09:56:37.827 回答