Download PHP generated webpage as HTML file
20,465
Solution 1
<?php
$filename = 'filename.html';
header('Content-disposition: attachment; filename=' . $filename);
header('Content-type: text/html');
// ... the rest of your file
?>
Just put the above code on the top of your PHP file.
Solution 2
You can try this with file_get_contents();
<?php
//Link to download file...
$url = "http://example.com/test.php";
//Code to get the file...
$data = file_get_contents($url);
//save as?
$filename = "test.html";
//save the file...
$fh = fopen($filename,"w");
fwrite($fh,$data);
fclose($fh);
//display link to the file you just saved...
echo "<a href='".$filename."'>Click Here</a> to download the file...";
?>
Author by
MeltingDog
Updated on July 01, 2020Comments
-
MeltingDog almost 4 years
I am using a PHP based CMS which uses
<include>
to add the header and footer of the page, and the content of page is retrieved from a database using PHP/MySQL.I want to create a button on the page that downloads the page as a HTML file - just like what you would get if you copied the page source onto a blank file or saved the page with your browser.
Normally I would use PHP to locate the file and download it, as this is a CMS generated page these is no actual file.
Does anyone know how to achieve this?
(ps - the aim of this is to create a downloadable HTML email file)
-
Abhishek Saha over 11 yearsHe wants to download on click of a button. Your logic will make one extra request.
-
Zorji over 11 yearsI thought his problem was unable to download the file. You know when you are directed to an HTML file the browser will open it instead of download it. So my code force the browser to download it.
-
Abhishek Saha over 11 yearsI agree to what you say. Might be his solution is a mix of (both of our solution). My solution will prepare the file and the link. On clicking the link he will be directed to your page where it will force him to download.
-
Zorji over 11 yearsI agree, it's a mixture of both.
-
SagarPPanchal almost 11 yearsIf fonts in PHP file containing 'UFT8' Characters, then is this code will properly for generating HTML?
-
Zorji over 8 years@Bholu I think you mean the filename contains utf8 chars? If filename contains utf8 chars, this will only affected the name of the downloaded file.