写一个文本文件并强制下载php

ste*_*vey 20 php

我使用按钮指向创建文本文件的脚本:

<?php
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
?>
Run Code Online (Sandbox Code Playgroud)

之后我想让网页浏览器建议下载或打开这个文件我该怎么办?谢谢

Mih*_*rga 40

使用readfile()application/octet-stream标头

<?php
    $handle = fopen("file.txt", "w");
    fwrite($handle, "text1.....");
    fclose($handle);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename('file.txt'));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('file.txt'));
    readfile('file.txt');
    exit;
?>
Run Code Online (Sandbox Code Playgroud)


Eds*_*ina 5

$content = file_get_contents ($filename);
header ('Content-Type: application/octet-stream');
echo $content;
Run Code Online (Sandbox Code Playgroud)

应该管用