Search code examples
phprestler

have Restler method return a Content-Disposition header


In one of my get methods is it possible to specify a specific Content-Type and Content-Disposition? After getting my data back I'm doing this:

return Scope::get('CsvFormat')->encode($data);

and so the data returned is in a CSV format. Now I want to set the content type to text/csv and set a Content-Disposition so that it actually allows the file download, instead of just showing the content.


Solution

  • Here is a working example!

    In Excel.php

    <?php
    
    class Excel
    {
        /**
         * Download CSV data which can be rendered with Excel
         *
         * @return array
         * @format CsvFormat
         * @header Content-Disposition: attachment; filename="excel.csv"
         */
        public function download()
        {
            //csv compatible array
            $data = [['name' => 'John Doe', 'age' => '23'], ['name' => 'Mika', 'age' => '45']];
    
            return $data;
        }
    }
    

    Your index.php

    <?php
    
    require '../vendor/autoload.php';
    
    use Luracast\Restler\Restler;
    
    $r = new Restler();
    $r->addAPIClass('Excel');
    
    $r->setOverridingFormats('CsvFormat');
    $r->handle();
    

    Try http://localhost/excel/download