0

I want to generate and download a html or a php file when a controller is called. Any help would be appreciated.

1 Answer 1

1
<?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
        );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.