May 25, 2017

How to make php file to export CSV data

Very easy way to make an php file and export data on throwing the data to this url.
Please copy and paste below file to the server and send data variables to this path.

Like i have uploaded it as export.php

Send the two variable csv_header and csv_output as comma saperaed string and new line must be defined by ‘\n’

In case of document compatibility you should use PHP_EOL function instead of ‘\n’

$csv_header= ‘ID,NAME,AGE’;


$csv_output .=’1,Mark,25′.’\n’;

$csv_output .=’1,Jackob,24′.’\n’;

$csv_output .=’1,Prince,26′.’\n’;

<form action=”http://www.shakalya.com/export.php”>

<input type=”hidden” name=”csv_header” value=”<?php echo $csv_header ?> “/>

<input type=”hidden” name=”csv_output” value=”<?php echo $csv_header ?> “/>

<input type=”submit”  value=”export”/>



This file will generate our CSV table. There is nothing to display on this page, it is simply used
to generate our CSV file and then exit. That way we won’t be re-directed after pressing the export
to CSV button on the previous page.

//First we’ll generate an output variable called out. It’ll have all of our text for the CSV file.
$out = ”;

//Next let’s initialize a variable for our filename prefix (optional).
$filename_prefix = ‘csv’;

//Next we’ll check to see if our variables posted and if they did we’ll simply append them to out.
if (isset($_POST[‘csv_header’])) {
$out .= $_POST[‘csv_header’];
$out .= “\n”;

if (isset($_POST[‘csv_output’])) {
$out .= $_POST[‘csv_output’];

//Now we’re ready to create a file. This method generates a filename based on the current date & time.
$filename = $filename_prefix.”_”.date(“Y-m-d_H-i”,time());

//Generate the CSV file header
header(“Content-type: application/vnd.ms-excel”);
header(“Content-Encoding: UTF-8”);
header(“Content-type: text/csv; charset=UTF-8”);
header(“Content-disposition: csv” . date(“Y-m-d”) . “.csv”);
header(“Content-disposition: filename=”.$filename.”.csv”);
//echo “\xEF\xBB\xBF”;
// UTF-8 BOM
//Print the contents of out to the generated file.
print $out;

//Exit the script


You may also like...