首页 > 解决方案 > 使用 Laravel 生成和下载 XML 文件

问题描述

我正在尝试使用 Laravel 生成 XML 文件。从控制器开始,我在其中生成需要在 XML 文件上使用的数据。我使用刀片模板生成 XML 文件,但无法保存文件或自动下载


$xml_datos = [];
$total = 0;

.
.
.

$output = View::make('site.contabilidad.adeudosXML')->with(compact('xml_datos', 'total'))->render();

$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n <Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.008.001.02\">" .$output;

return $xml;

我需要下载文件,而不是显示。我尝试过使用 Storage 和 Filesystem 类,但它们似乎都不起作用

标签: phpxmllaravel

解决方案


您可以像这样创建一个响应

 public function saveXML()
    {
        $output = View::make('site.contabilidad.adeudosXML')->with(compact('xml_datos', 'total'))->render();

        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n <Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.008.001.02\">" .$output;

        $response = Response::create($xml, 200);
        $response->header('Content-Type', 'text/xml');
        $response->header('Cache-Control', 'public');
        $response->header('Content-Description', 'File Transfer');
        $response->header('Content-Disposition', 'attachment; filename=' . yourFileNameHere . '');
        $response->header('Content-Transfer-Encoding', 'binary');
        return $response;
    }

此外,我强烈建议您使用PHP 函数来操作 XML


推荐阅读