PHP: Getting HTML code in file while writing a .txt file -
i new php, want write text file , download @ same time clicking on button that, wrote function in php create text file , write content in , start downloading when file generated. writing content want issue is writing html code in file.
my function write file below
function generatereportfile($content){ $filename="test.txt"; $handle = fopen($filename,'w') or die("can't open files"); fwrite($handle, $content); fclose($handle); header('content-type: application/octet-stream'); header('content-disposition: attachment; filename='.basename($filename)); header('expires: 0'); header('cache-control: must-revalidate'); header('pragma: public'); header('content-length: ' . filesize($filename)); readfile($filename); exit; }
and calling function @ home page index.php , code :-
<html> <head> <title> formatted report generator </title> </head> <body> <form action="" method="post"> <input type="text" name="txtheadertext" placeholder="header text"/><br/> <input type="number" name="txttotalrows" title="total number of required rows"/> <button name="btn_generatefields">generate fields</button><br/> <button name="btn_generatefile">generate file</button> </form> </body> </head> </html> <?php /* * change license header, choose license headers in project properties. * change template file, choose tools | templates * , open template in editor. */ require_once './functions/generalfunctions.php'; $genfunc = new generalfunctions(); if(isset($_post['btn_generatefields'])){ echo $genfunc->generateformattedhtmlform(4); } // writing file if(isset($_post['btn_generatefile'])){ $content = "hi ravi bhushan , report portal"; $genfunc->generatereportfile($content); }
now when clicking on generate file button generating file in writing html code of index.php , after writing content passing in generatereportfile function.
also when removing following code generatereportfile($content) function writing file on local drive proper output.
header('content-type: application/octet-stream'); header('content-disposition: attachment; filename='.basename($filename)); header('expires: 0'); header('cache-control: must-revalidate'); header('pragma: public'); header('content-length: ' . filesize($filename)); readfile($filename); exit;
the problem can not send headers after sending text (html, text ... ) . have send first html, , ( example javascript , redirect php send file. way ( not ) , work.
the redirect force download , url stays in place.
Comments
Post a Comment