Download file empty

CakePHP 4
php 8
Query result coming but downloaded file empty.

public function export($format = 'json')
    {

        $format = strtolower($format);
        $formats = [
            'xml' => 'Xml',
            'json' => 'Json',
        ];

        if (!isset($formats[$format])) {
            throw new NotFoundException(__('Unknown format.'));
        }

        $this->viewBuilder()->setClassName($formats[$format]);
        $visitors = $this->Visitors->find();
        // dd($visitors->toArray());
        $this->set(compact('visitors'));
        $this->viewBuilder()->setOption('serialize', ['visitors']);
        return $this->response->withDownload('report-' . date('YmdHis') . '.' . $format);
    }

replace the return with

$this->response = $this->response->withDownload('report-' . date('YmdHis') . '.' . $format);

The view is rendered if your controller action doesn’t return or return null