Search code examples
phpxmllaravelresponse

Assign filename dynamically in a response


in my web application created with Laravel 8, I need to download an .xml file and the file name must be dynamically created, as per the title. this is because the file name is composed following a specific rule and having to include today's date.

$filename = 'FirstPart_'.date("Y-m-d").'_000.xml'

so far to test the response and therefore the download I have given a fixed name to the file, as follows, and the download is performed correctly.

  • code with fixed filename
        $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="TestXMLDownload.xml"');
        $response->header('Content-Transfer-Encoding', 'binary');
        return $response;

But when i try to download the file with my custom filename, the download fails.

  • code with custom filename
        $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="".$filename.""');
        $response->header('Content-Transfer-Encoding', 'binary');
        return $response;

I appreciate any suggestion or advice


Solution

  • Your code have a error in this line, In this case "$filename" append in your header not dynamic file name value.

    $response->header('Content-Disposition', 'attachment; filename="".$filename.""');
    

    try this solution:

    $filename = "TestXMLDownload.xml";
    
    $response = Response::create($xml, 200);
    $response->header('Content-Type', 'text/xml');
    $response->header('Cache-Control', 'public');
    $response->header('Content-Description', 'File Transfer');
    
    //change that line in your code
    
    $response->header('Content-Disposition', 'attachment; filename=' . '"' . $filename . '"');
    
    $response->header('Content-Transfer-Encoding', 'binary');
    
    return $response;
    

    Append $filename in your filename that pass tp $response->header.