Question

I want user to be able to download a file which is generated on the fly ( not stored at the server).

In order to do so I created test case simple website with form and a submit button.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Some Test tittle</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<div>
<div>
<form action='/thispage.php' method='post' class='asholder' enctype="multipart/form-data">
<input type='submit' value='Generate' name='generatetxt'>
</form>
</div>

</div>

<div id='bottom-bar'></div>

</html>

Then I have created condition to execute createTxt method everytime when in $_POST will be generatetxt field:

if (in_array('generatetxt',$_POST)){
    ob_end_clean();
    createTxt("some other text");
    ob_flush(); 
}

and the createTxt function

function createTxt($profile){
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment;filename="test.txt"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0

    echo "SOME TEXT SOME TEXT SOMTE TEXT SOME TEXT\n";
    echo $profile;
}

However everytime user is downloading .txt file he gets something like:

SOME TEXT SOME TEXT SOMTE TEXT SOME TEXT
some other text
</div>

</div>

<div id='bottom-bar'></div>

</html>

Can anyone give me a hint how I can use output buffer to remove html tags from the downloaded file content?

Was it helpful?

Solution

No need for output buffering. You can strip html tags off from $profile when echoing it (using strip_tags function)

echo strip_tags($profile);

Also do not forget to have an exit call after you output txt content.

createTxt($profile);
exit;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top