您的代码实际上在服务器上创建了一个文件,之后它不会被删除。如果代码失败,则可能是您没有在服务器上写入的权限。您可以将代码缩减为以下内容,以免在此过程中生成文件:
<?php
if(isset($_POST['text']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text'];
exit; //stop writing
}
?>
<html>
<body>
<form action="" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
</body>
</html>
首先,您应该在屏幕上打印任何内容之前输出文件,其次,您忘记添加name="submit"
到原始代码中。我没有在这里使用它,但我包括在内让您了解一下。
在 WordPress 上下文中:将其添加到您的
functions.php
或插件文件中:
function feed_text_download(){
if(isset($_POST['text_to_download']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action('after_setup_theme', 'feed_text_download');
将表单添加到您的模板文件之一或帖子的 HTML 编辑器中:
<form action="" method="post">
<textarea name="text_to_download" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
应该不错:)
编辑:添加文件名
HTML:
<form action="" method="post">
<label>Filename:<input type="text" name="filename" /></label>
<label>Text:<textarea cols="100" name="text_to_download" rows="20"></textarea></label>
<input type="submit" name="submit" value="Download Text" />
</form>
PHP:
function feed_text_download() {
if ( isset( $_POST['text_to_download'] ) && isset( $_POST['filename'] ) ) {
$filename = sanitize_file_name( $_POST['filename'] );
header( 'Content-disposition: attachment; filename=' . $filename );
header( 'Content-type: application/txt' );
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action( 'after_setup_theme', 'feed_text_download' );