Output CSV straight to browser using PHP

If you want a user to download a CSV, but do not want to have to generate it on the filesystem first, you can output the CSV directly to the browser by writing it to PHP’s output stream.

If you set the resource for the normal PHP CSV functions as the PHP output stream you can use output buffering to then save it into a string. You can then output this straight to the browser along with the appropriate CSV response headers.

3 comments