How to create and download a csv file from php script? - php

I am a novice programmer and I searched a lot about my question but couldn't find a helpful solution or tutorial about this.
My goal is I have a PHP array and the array elements are showing in a list on the page.
I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.
I don't know how to do this. I have searched a lot too. But yet to find any helpful resource.
Please provide me some tutorial or solution or advice to implement it by myself. As I'm a novice please provide easy to implement solutions.
My array looks like:
Array
(
[0] => Array
(
[fs_id] => 4c524d8abfc6ef3b201f489c
[name] => restaurant
[lat] => 40.702692
[lng] => -74.012869
[address] => new york
[postalCode] =>
[city] => NEW YORK
[state] => ny
[business_type] => BBQ Joint
[url] =>
)
)

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:
$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line);
}
To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):
header('Content-Disposition: attachment; filename="filename.csv";');
Putting it all together:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: text/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And you can use it like this:
array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);
Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}

I don't have enough reputation to reply to #complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.
Correct line should look like this:
header('Content-Disposition: attachment;filename="'.$filename.'";');
In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:
header('Content-Type: application/csv; charset=UTF-8');
Also, I find it more elegant to use rewind() instead of fseek():
rewind($f);
Thanks for your solution!

Try...
csv download.
<?php
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
$data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>

That is the function that I used for my project, and it works as expected.
function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
header( 'Content-Type: application/csv' );
header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
// clean output buffer
ob_end_clean();
$handle = fopen( 'php://output', 'w' );
// use keys as column titles
fputcsv( $handle, array_keys( $array['0'] ), $delimiter );
foreach ( $array as $value ) {
fputcsv( $handle, $value, $delimiter );
}
fclose( $handle );
// flush buffer
ob_flush();
// use exit to get rid of unexpected output afterward
exit();
}

Use the below code to convert a php array to CSV
<?php
$ROW=db_export_data();//Will return a php array
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
$fp = fopen('php://output', 'w');
foreach ($ROW as $row) {
fputcsv($fp, $row);
}
fclose($fp);

If you're array structure will always be multi-dimensional in that exact fashion, then we can iterate through the elements like such:
$fh = fopen('somefile.csv', 'w') or die('Cannot open the file');
for( $i=0; $i<count($arr); $i++ ){
$str = implode( ',', $arr[$i] );
fwrite( $fh, $str );
fwrite( $fh, "\n" );
}
fclose($fh);
That's one way to do it ... you could do it manually but this way is quicker and easier to understand and read.
Then you would manage your headers something what complex857 is doing to spit out the file. You could then delete the file using unlink() if you no longer needed it, or you could leave it on the server if you wished.

Update for UTF-8 Encoding
Updating #complex857 's answer
function array_to_csv_download($array, $filename = "export.csv", $delimiter=",") {
header('Content-Disposition: attachment; filename="'.$filename.'";');
header('Content-Type: application/csv; charset=UTF-8');
// open the "output" stream
$f = fopen('php://output', 'w');
// Write utf-8 bom to the file
fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF));
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
May be a bit ugly code but it works!

This function can generate a downloadable CSV file, you can set up the name and the delimiter without tricky functions (UTF-8 encoding in header function).
/**
* Array2CSVDownload
*
*/
function Array2CSVDownload($array, $filename = "export.csv", $delimiter=";") {
// force object to be array, sorry i was working with object items
$keys = array_keys( (array) $array[0] );
// use keys as column titles
$data = [];
array_push($data, implode($delimiter, $keys));
// working with items
foreach ($array as $item) {
$values = array_values((array) $item);
array_push($data, implode($delimiter, $values));
}
// flush buffer
ob_flush();
// mixing items
$csvData = join("\n", $data);
//setup headers to download the file
header('Content-Disposition: attachment; filename="'.$filename.'";');
//setup utf8 encoding
header('Content-Type: application/csv; charset=UTF-8');
// showing the results
die($csvData);
}

Related

fput csv output file recommended path for sensitive files

I have a query that returns an array which is then processed by this function to ultimately write the output to a csv file. My question is about the path of the output file, it should not be accessible via the web root hence the idea to have the path as /tmp/ instead? Or should I create a new folder specifically for the uploads outside of the web root? So basically I just want to make sure that no one browsing our website, which is pretty much locked down anyway to specific ip's can access the csv files generated by this function. P
$date = date("Y-m-d H:i:s");
$file = $date . ".csv";
function array_to_csv_download($array, $filename, $delimiter = ",")
{
header("Content-Type: application/csv");
header('Content-Disposition: attachment; filename="' . $filename . '";');
$u = "/tmp/" . $filename;
// open the "output" stream
$f = fopen($u, "a");
$csv = array_map("str_getcsv", file($u));
if (isset($csv[0])) {
//do nothing
} else {
//header
$fields = ["Name", "Contact Number"];
fputcsv($f, $fields, $delimiter);
}
//content
foreach ($array as $line) {
//foreach ($array as $header => $line)
fputcsv($f, $line, $delimiter);
}
}
array_to_csv_download($customer_id_result, $file);
P.S. Hope I can post this type of question here, if not please advise on which site part of the group

How to export multiple csv files at once

This exports one file with 2 rows in it. How can export 2 files each with one row in it?
<?php
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen("contacts.csv","w");
foreach ($list as $line) {
fputcsv($file, $line);
}
fclose($file);
?>
I tried this:
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen('php://output', 'w');
$i = 1;
foreach ($list as $line) {
header('Content-Disposition: attachment; filename="' . $i . 'wp.csv"');
fputcsv($file, $line);
fclose($file);
$i++;
}
But it only downloads one file. At least it only has the one row in it though.
I found this example. Even though it creates 2 separate csv files, the data is identical in each file instead of each file containing an individual record.
// some data to be used in the csv files
$headers = array('id', 'name', 'age', 'species');
$records = array(
array('1', 'gise', '4', 'cat'),
array('2', 'hek2mgl', '36', 'human')
);
// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {
// create a temporary file
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
// write the data to csv
fputcsv($fd, $headers);
foreach($records as $record) {
fputcsv($fd, $record);
}
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
You can only put one "file" into an HTTP response.
If you want to generate multiple CSV files then you'll need to get more exotic. You could generate a HTML document of links to URLs that each generate a CSV file, or you could generate a zip file containing the CSV files.
Just make a new File and use it like this
$file2 = fopen("contacts2.csv", "w");
fputcsv($file2, $list[1]);
You always write in the same file here, because you are refering to $file
fputcsv($file, $list[1]);

How to put array into CSV file and echo it out into an href?

I want to put an array into a csv file, and echo it out in a href link, that file, to download it when I press on that link. How can I do that?
I have this code:
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
If I use this, It will directly download me a csv file that contains my array. How can I put this into a href link? Thanks.
You could use GET parameter to decide whether to produce the file contents, like you do now, or produce the HTML with a link to the same page, but with the additional GET parameter.
Something like the following:
if (isset($_GET('download')) {
// your original code:
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
} else {
// get current page URL and append the download parameter
$href = $_SERVER['PHP_SELF'] . "?download=1";
// output the HTML hyperlink, which will lead to the above `if` code
?>
download CSV
<?php
}
?>
The above code assumes that your "non-download" request does not have any URL arguments, otherwise you need to add the download argument with an ampersand. You should also manage the hash character, if you use it in your URL.

Array-to-CSV-export function is facing an issue in WordPress-plugin

I am using a simple array-to-CSV-export function in my plugin page for generating a report .
When I am running this code I am getting an error that it will export whole html content along with my expected array.
Here is my code:
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
clearstatcache();
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($input_array as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line, $delimiter);
}
//echo '<pre>';
//print_r($temp_memory); exit;
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send file to browser for download */
fpassthru($temp_memory);
}
/** Array to convert to csv */
$array_to_csv = Array(
Array(12566,
'Enmanuel',
'Corvo'
),
Array(56544,
'John',
'Doe'
),
Array(78550,
'Mark',
'Smith'
)
);
clearstatcache();
convert_to_csv($array_to_csv, 'report.csv', ',');
I'm guessing that WP is carrying on with its normal operations after this function is called so you'll get the HTML template output after the CSV. Putting in an exit statement after fpassthru should do it, but you need to be careful that this doesn't mess up anything else that Wordpress does at the end of each page response. Drupal for example has a drupal_exit() function for just this purpose. I'm not familiar enough with WP to know for sure, but the documentation for the wp_die() function suggests that you can use PHP exit without too many problems
You can use this code to generate excel file with .xlsx extension
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.12/xlsx.core.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var insuranceArray = new Array(insuranceInfo);
var bills = db.bills;
//Create tabs in excel file
var opts = [{sheetid:'Insurance Information',header:true},{sheetid:'bills Info',header:false}];
alasql('SELECT * INTO XLSX("Data.xlsx",?) FROM ?', [opts, insuranceArray,bills]]);
// Close the window once you save the file
window.onfocus=function(){
window.close();
}
</script>
This code works for me...
Try this at the top of the export function.
global $wpdb;
$wpdb->hide_errors();
#set_time_limit(0);
if ( function_exists( 'apache_setenv' ) )
#apache_setenv( 'no-gzip', 1 );
#ini_set('zlib.output_compression', 0);
//#ob_clean();
#ob_end_clean(); // to prevent issue that unidentified characters when opened in MS-Excel in some servers
header( 'Content-Type: text/csv; charset=UTF-8' );
header( 'Content-Disposition: attachment; filename=export.csv' );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
$fp = fopen('php://output', 'w');
Most simplest way to generate csv without saving the file on the server
<?php
$array = Array(
Array(
12566,
'Enmanuel',
'Corvo'
),
Array(
56544,
'John',
'Doe'
),
Array(
78550,
'Mark',
'Smith'
)
);
arr_to_csv($array);
function arr_to_csv($array)
{
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
$fp = fopen('php://output', 'w');
foreach ($array as $row) {
fputcsv($fp, $row);
}
}

Building CSV with array

I need to run a query that will return multiple rows and export it to a CSV. I have to put the cells in a certain order though.
So lets say my table is laid out id, name, address, wife. I need to build a csv in the order of id, address, wife, name. I figured I could just make an array in the correct order and then make a csv with that but after an hour of googling i cant find out how to make a csv with an array.
There is fputcsv but that requires a pre-made csv. Also, i was hoping there was a codeigniter way of doing it.
public function export() {
$this->load->helper('download');
$data[1] = 'i like pie';
$data[2] = 'i like cake';
force_download('result.csv', $data);
}
I tried that but the error said the download helper file was expecting a string not an array.
Here's some code I use... you could adjust the columns you need in the export...
Note: This CSV is directly sent to php://output which writes directly to the output buffer. This means you're not saving any .csv files on the server and it can handle a much larger file size that building a giant array and then trying to loop through it.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"Jobs_".date('M.j.y', $from)."-".date('M.j.y', $to).".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
fputcsv($handle, array(
'JobId',
'Template',
'Customer',
'Status',
'Error',
'PDF',
'Run Time',
'Wait Time',
'Server'
));
foreach ($jobs as $jobData) {
fputcsv($handle, array(
$job->getId(),
$job->getTemplate(),
$jobData['customers_firstname'].' '.$jobData['customers_lastname'],
$status,
$error,
$jobData['products_pdfupload'],
$job->getRunTime(),
$job->getWaitTime(),
$jobData['server']
));
}
fclose($handle);
exit;
This should give you a good mental picture of how a CSV export works. I don't use CodeIgniter's file download helper, so I can't help you on that front.
This short scripts build the CSV and allows you to download it also:
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($input_array as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line, $delimiter);
}
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send file to browser for download */
fpassthru($temp_memory);
}
/** Array to convert to csv */
$array_to_csv = Array(Array(12566, 'Enmanuel', 'Corvo'), Array(56544, 'John', 'Doe'), Array(78550, 'Mark', 'Smith'));
convert_to_csv($array_to_csv, 'report.csv', ',');
You can read the full post here:
PHP Array to CSV - Download
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>

Categories