简体   繁体   中英

how to download html file in php

I'm creating a doc file with the php.

I'm using echo to output everything but I can see that my html is properly created in my response but the download is not starting.

How can I make this download to start?

Part of my code:

header('Content-Description: File Transfer'); 
header("Content-type: application/msword; charset=utf-8");
header("Content-Disposition: attachment;Filename=test.doc");

echo $main_html; //html code

I tested this, and it works perfect.

file_put_contents("test.doc",$main_html);
header('Content-Description: File Transfer');
header("Content-type: application/msword; charset=utf-8");
header("Content-Disposition: attachment;Filename=test.doc");
readfile("test.doc");
unlink("test.doc");
die;

Note : if you may already know, header only works before passing any output to the browser, including line break and even a space .

To start an download, you have to use the content-type application/octet-stream to start an download as mentioned in RFC 2046 .

Btw. you have to echo the content of the doc file and not your html content(ie use readfile('test.doc') as mentioned in other answers or simply echo the content of your doc file)

Use this:

header("Content-Type: text/html"); 
header("Content-Disposition: attachment; filename=read.html;"); 
header("Content-Transfer-Encoding: binary");

echo $html;

Your code works fine for me.. I ran this on my server

<?php
$main_html = "<h1>Hey I'm Nate</h1>"; // I did put this in
header('Content-Description: File Transfer'); 
header("Content-type: application/msword; charset=utf-8");
header("Content-Disposition: attachment;Filename=test.doc");

echo $main_html; //html code

Did you define $main_html before echoing? Because all I changed was added some html to it.

It started a download right away, with the correct content in the document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM