5

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)

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

2 Answers2

8
<?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.

Zorji
  • 1,002
  • 10
  • 18
  • He wants to download on click of a button. Your logic will make one extra request. – Abhishek Saha Oct 26 '12 at 05:20
  • I 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. – Zorji Oct 26 '12 at 05:50
  • 1
    I 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. – Abhishek Saha Oct 26 '12 at 06:00
  • 1
    I agree, it's a mixture of both. – Zorji Oct 26 '12 at 12:04
  • If fonts in PHP file containing 'UFT8' Characters, then is this code will properly for generating HTML? – SagarPPanchal Jul 19 '13 at 06:19
  • @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. – Zorji Oct 30 '15 at 06:18
6

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...";

?>
Abhishek Saha
  • 2,564
  • 1
  • 19
  • 29