3

I'm trying to generate a XML file using Laravel. Starting from the Controller, where I generate the data that I need to use on the XML file. I generate the XML file using a blade template but I can't save the file or download it automatically


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

I need the file to be downloaded, not showed. I've tried using the class Storage and Filesystem but none of them seems to work

Mahoor13
  • 5,297
  • 5
  • 23
  • 24
Fran
  • 29
  • 1
  • 1
  • 4
  • 1
    https://laravel.com/docs/5.8/filesystem#retrieving-files has a section "Downloading Files", see if that helps. Or use headers: https://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header – brombeer Apr 23 '19 at 10:41

1 Answers1

3

You could create a Response like this:

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

Also, i strongly recommend you using the PHP functions to manipulate XML.

Mahoor13
  • 5,297
  • 5
  • 23
  • 24
Piazzi
  • 2,490
  • 3
  • 11
  • 25