返回一个 xml 文件,避免回显它

标记

我知道不应该echo在控制器中使用,但我不明白我应该使用什么来返回 xml 以便下载它。请注意,它不是服务器上的文件,它只是一个字符串:

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;
}

它实际上按预期工作:浏览器下载具有给定文件名的文件,其内容是$xml值。

但是在文件的末尾有关于标题的警告:

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]

据我所知,这是由于使用了echoin 控制器。可能会发生在发送标头之前有一个输出,然后是警告。

替换echo函数的正确方法是什么?

马克西米利安·菲克斯

只需使用die()exit()

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);

    if (!headers_sent())
    {
        header('Content-type: text/xml');
        header('Content-Disposition: attachment; filename="' . $fpr->getFilename() . '"');
    }
    else
    {
        //Do something else to let them know they can't expect a file
        die();
    }

    die($fpr->asXML());
}

更新

关于评论

在这个问题php-exit-or-return-which-is-better , what-are-the-differences-in-die-and-exit-in-php 中已经详细解释了使用return , exitdie

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章