HTML Content to a Save As / Open Dialog

I had a project that required outputting an HTML content so that the Open/Save As dialog box would be shown.  This is what I did; I post it here for my own reference (and for anyone else that comes along). The code block below is as a function, where the $post_output is the entire HTML content you want to use with the Open/Save As dialog.

 
 
// --------------------------------------------------------------------------------
// output the file with a prompt to save
function blogtohtml_output_file($post_output = "nothing found")
{
$thefile = 'blogexport_' . date('m-d-Y_his') . '.html' ;
if ( headers_sent())
{
throw new Exception('Uh-oh...headers already sent. 🙁 ') ;
}
$size = strlen($post_output) ;
header('Content-Description: File Transfer') ;
header('Content-Type: application/octet-stream') ;
header('Content-Disposition: attachment; filename=' . $thefile) ;
header('Content-Transfer-Encoding: binary') ;
header('Connection: Keep-Alive') ;
header('Expires: 0') ;
header('Cache-Control: must-revalidate, post-check=0, pre-check=0') ;
header('Pragma: public') ;
header('Content-Length: ' . $size) ;
ob_clean() ;
flush() ;
echo $post_output ;
exit ;
return ;
}

The code sets up a filename that will be used with the Save As choice. If headers are already sent, an  error is shown (you can’t have any output to the screen when you use the Header Content commands.

Note that the last four lines are required in order to use this function within other code.

Works quite well, so it’s here to be available the next time I need it.

Leave a Reply

Name and email are required. Your email address will not be published.