I know one should not use echo
in controllers, but I don't understand what I should use to return an xml in order to download it. Please note, it's not a file on the server, it's just a string:
public function export()
{
$this->autoRender = false;
$id = $this->request->getQuery('id');
$invoice = $this->Invoices->get($id, ['contain' => ['Customers', 'ItemInvoices' => ['ItemProformas' => ['ItemDeliveryNotes' => ['ItemOrders' => ['Orders' => ['Customers']]]]]]]);
$fpr = new ExportInvoice();
$fpr->SetInvoice($invoice);
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="' . $fpr->getFilename() . '"');
$xml = $fpr->asXML();
echo $xml;
}
it actually works as expected: the browser download a file with the given filename and its content is the $xml
value.
But at the end of the file there are warnings about headers:
Warning (512): Unable to emit headers. Headers sent in file=/home/mark/myproject/src/Controller/InvoicesController.php line=130 [CORE/src/Http/ResponseEmitter.php, line 51]
Warning (2): Cannot modify header information - headers already sent by (output started at /home/mark/myproject/src/Controller/InvoicesController.php:130) [CORE/src/Http/ResponseEmitter.php, line 152]
Warning (2): Cannot modify header information - headers already sent by (output started at /home/mark/myproject/src/Controller/InvoicesController.php:130) [CORE/src/Http/ResponseEmitter.php, line 181]
Warning (2): Cannot modify header information - headers already sent by (output started at /home/mark/myproject/src/Controller/InvoicesController.php:130) [CORE/src/Http/ResponseEmitter.php, line 181]
As far as I know this is due to the usage of echo
in controller. It may happens there's an output before sending the header, and then the warnings.
What's the correct way to replace the echo
function?