You cannot use WP_REST_Response
to do this. It is however possible to return something else with the rest api.
If you're absolutely sure you have the complete response ready (including headers, like Content-Disposition
for downloads), you can simply exit;
after generating the final response. Do note that this completely bypasses any hooks that would've been called afterwards, so use with caution.
An example with .csv
$filename = 'example-file.csv';
header("Access-Control-Expose-Headers: Content-Disposition", false);
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
// output starts here, do not add headers from this point on.
$csv_file = fopen('php://output', 'w');
$csv_header = array(
'column-1',
'column-2',
'column-3',
);
fputcsv($csv_file, $csv_header);
$data = array(
array('a1', 'b1', 'c1'),
array('a2', 'b2', 'c2'),
array('a3', 'b3', 'c3'),
);
foreach ($data as $csv_data_entry) {
fputcsv($csv_file, $csv_data_entry);
}
fclose($csv_file);
// With a non-file request, you would usually return the result.
// In this case, this would cause the "Headers already sent" errors, so an exit is required.
exit;