We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 26503
    • 620 Posts
    I'm trying to generate and push a CSV file [report] to the browser, I place this in a snippet:

    if (file_exists($filename)) {echo 'reading file';
     header('Content-Description: File Transfer');
     header('Content-Type: text/csv');
     header('Content-Disposition: attachment; filename='.basename($filename));
     //header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     header('Content-Length: ' . filesize($filename));
     ob_clean();
     flush();
     readfile($filename);
    }


    Snippet:

    [[!downloadReport? &filename=`[[!getVariable? &var=`report`]]`]]


    but what I get back looks is just the page I am submitting the download request from back.

    the file does exist
    the correct file will download IF I place an exit(); after the download code.
    I'm thinking this is happening because modx has already sent the headers?

    How do I fix this?
      *** Not just websites, we also create signage, banners, print, trade show displays and more! ***

      Sean Kimball CLP, CLS.
      Technical Director / Sr. Developer | BigBlock Studios
      ._______________________________________________.
      Bigblock Studios http://www.bigblockstudios.ca Web site design & development.
      27-1300 King Street East. Box 167 Oshawa, Ontario L1H8J4 Canada.
      phone/fax: 905-426-5525
      • 40045
      • 534 Posts
      By making the changes to core/model/modx/modfilehandler.class.php which I proposed here: https://github.com/modxcms/revolution/pull/11371


      then you could create a snippet "getDownload" with the code

      $modx->getService('file', 'modFileHandler');
      
      // if you generate the data afterwards (inside this snippet 
      // the download path doesn't matter as no physical file is ever created...)
      $fileobj = $modx->file->make(MODX_BASE_PATH . $download);
      // or in your specific case
      // $fileobj = $modx->file->make($modx->runSnippet('getVariable', array('var' => 'report')));
      
      // you could generate your data here (the csv)
      // and make a temporary file (not in the filesystem) like
      // $csvdata = 'csvstring;etc;bla'
      // $fileobj->setContents($csvdata);
      
      $fileobj->download();
      


      and then call it like:

      [[!getDownload? &download=`assets/file.csv`]]
      
      [ed. note: exside last edited this post 9 years, 11 months ago.]