加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:20:08 所属栏目:PHP教程 来源:网络整理
导读:我正在研究如何从字符串创建文件的方法,这可能是纯文本将保存为.txt和 PHP为.php等,但我希望得到一些洞察力 **我找到了这段代码 $file = 'people.txt';// Open the file to get existing content$current = file_get_contents($file);// Append a new person
我正在研究如何从字符串创建文件的方法,这可能是纯文本将保存为.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 Smithn";
// 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尝试下载包含$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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读