What is the recommended approach to allow users to download HTML code generated by PHP instead of displaying it on a webpage?

To allow users to download HTML code generated by PHP instead of displaying it on a webpage, you can set the appropriate headers in PHP to force the browser to treat the output as a file download. This can be achieved by setting the Content-Type header to 'text/html' and the Content-Disposition header to 'attachment'. This will prompt the user to download the HTML code as a file instead of rendering it in the browser.

<?php
// Generate the HTML code here
$htmlCode = "<html><body><h1>Hello, World!</h1></body></html>";

// Set the appropriate headers to force download
header('Content-Type: text/html');
header('Content-Disposition: attachment; filename="downloaded_html.html"');

// Output the HTML code
echo $htmlCode;