简体   繁体   中英

PHP - How to send textarea value with JavaScript AJAX and output it as .txt file for browser to download?

I have a textarea, text input and a button wich sends textarea and text input values (using AJAX post method) to PHP site. Now, I want PHP to output textarea value as .txt file so that it can be download via browser.

My PHP code looks like this:

$text=trim($_POST['text']);  // textarea value
$fileName=$_POST['fileName'].".txt";  // text input value
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header("Content-Length: ".mb_strlen($text));
print($text);

Nothing happens, so can you help me please. Thanks. :)

Have you considered not sending the text to the server and just creating a download client-side?

This post has some useful suggestions you could try to create a download by bypassing the server completely Create a file in memory for user to download, not through server

Maybe you should clean the buffer

while (@ob_end_clean());
ob_start();

header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header("Content-Length: ".mb_strlen($text));
print($text);

ob_end_flush();
exit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM