Tuesday 14 August 2018

Creating downloadable CSV files using PHP OR PHP create csv file and force download

How to download csv file in php
CSV (comma-separated values) is the most widely supported format for transferring tabular data between applications. The ability to export data in CSV format is a useful feature for many programs, and is becoming increasingly common in web applications. This page explains how to use PHP to create CSV files, and how to ensure that your visitor’s browser offers to download the file instead of displaying it.
The following code assumes that the data to be exported
$content  = "Dhara,Senjaliya";
$content .= "\n";
$content .= "Jainish,Senjaliya";
$content .= "\n\n";
$content .= "Successfully download";  

$filename = 'CSV_FILE_NAME.csv';

$mimeType = 'application/octet-stream';
header('Content-Type: application/vnd.ms-excel');
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="' . $filename . '"');

if (strstr($_SERVER['HTTP_USER_AGENT'],'MSIE'))
{
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
} else {
    header('Pragma: no-cache');
}

echo "$content"; 
die;

0 comments:

Post a Comment