testing
testing

Reputation: 2343

Download CSV using header does not work in PHP

I am trying to generate a CSV file on the fly and allow the user download it when an API is hit. Here is the user interaction that I imagined

User hit a button -> 
jquery do $.get to api -> 
api endpoint prepares data -> 
api endpoint pass in data to another function to generate csv

Here is my code so far

    public function test(){
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=file.csv");
        // Disable caching
        header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
        header("Pragma: no-cache"); // HTTP 1.0
        header("Expires: 0"); // Proxies;

        $f = fopen("php://output", "w");
        $test_data = array(
            array(
                 'something1' => '2'
           ),
            array(
                'somethign2' => '3'
            ),
        );
        foreach($test_data as $line){
            fputcsv($f, $line, ',');
        }
        fclose($f);

    }

I found that instead of downloading the csv, the browser simply renders the content of the result

2
3

when I view it in the network using Chrome.

I tried changing the content-type to force-download but still have the same result

Any help would be appreciated.

Thanks

Upvotes: 0

Views: 506

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You can't download stuff with ajax. This is a security feature (javascript cannot interact with the user's filesystem in any way). There are no plugins, no hacks, it can't be done.

Instead of trying to download the file with javascript you have to point the browser itself to the file. You can do that with a form if you need to pass data to the back...

$("#button").click(function(){
    $("<form id='hiddenform' action='myAPIEndpoint'><input type='hidden' name='parameter1' value='somevalue' /></form>")
        .apendTo("body");
    $("#hiddenform").submit(). remove();
});

Or if you don't need to pss any data to the backend you can use a regular link that points to your download page.

Upvotes: 2

Related Questions