HTML / PHP:单击按钮时打开下载文本文件框


HTML/PHP : open download text file box on button click

我试图为此找到一些东西,但没有成功......我只想创建一个内容,并让用户通过单击一个按钮将其下载到文本文件中,该按钮将打开一个经典的下载框。

我有我的 html 按钮 :

echo "<form name='"myform'" action='"myfile.php'" method='"POST'" enctype='"multipart/form-data'">";
echo "<input type='"hidden'" name='"phase2'" value='"1'">";
echo "<div class='"siej_upload_field'"><input type='"submit'" name='"submit'" value='"Save file'"></div>";

点击后的呼叫:

if( isset($_POST['phase2']) && $_POST['phase2']== 1)
{
    $file = 'mytextfile.txt';
    $content = 'content test';
    $res = file_put_contents($file, $content);
    echo 'result : '. $res . '<br/>';
}

但是,尽管我正确输入了此条件,但没有任何反应。我得到这个结果:

结果 : 12

那怎么办?感谢您的帮助...

试试这个。

<?php
        $file = 'mytextfile.txt'; #Place of the file or the post.
        if (file_exists($file)) 
        {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        }
    ?>