I want to generate and download a html or a php file when a controller is called. Any help would be appreciated.
1 Answer
<?php
declare(strict_types=1);
namespace Acme\StackExchange\Controller\Result;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\HTTP\Mime as HTTPMime;
class Download implements HttpGetActionInterface
{
protected Context $context;
protected FileFactory $fileFactory;
public function __construct(
Context $context,
FileFactory $fileFactory
) {
$this->context = $context;
$this->fileFactory = $fileFactory;
}
/**
* @inheritDoc
*/
public function execute()
{
// your generate logic
$fileName = 'your_file.html';
$fileContent = 'content of your HTML file';
return $this->fileFactory->create(
$fileName,
$fileContent,
DirectoryList::VAR_DIR,
HTTPMime::TYPE_OCTETSTREAM
);
}
}