phptextareatext-filessave-as

save contents of a textarea to a text file in php


I want to save the contents of a textarea to a text file in my client computer after clicking Save button. My code works but the HTML code is also included in the text file.

Here is my code:

if(isset($_POST['submit_save'])) {
$file = "output.txt";
$output = $_POST['output_str'];
file_put_contents($file, $output);
$text = file_get_contents($file);

header("Content-type: application/text");
header("Content-Disposition: attachment; filename=\"$file\"");
echo $text; 
} else {    
$_POST['output_str'] = "";
}

Example of a content from textarea to save:

The quick brown fox jumps over the lazy dog.

After clicking Save button, the "Save As" dialog box prompts and will save it as output.txt. Here's the content from output.txt:

The quick brown fox jumps over the lazy dog.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Save Textarea Content</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
.
.
. (all the way to </html>
</body>
</html>

How will I get rid of the html code in my saved text file?


Solution

  • change echo $text to die($text);