Exporting a session variable in a CSV file. PHP - php

I'm trying to export some data from my session array as a CSV but when I include the session_start() at the head of the file instead of creating a downloadable document it echoes it to the browser. Do I need to take a different approach or is there a way to fix this from happening? Without the session_start() it creates and downloads the file but its empty because my session array is missing.
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$filename\"" );
header("Pragma: no-cache");
header("Expires: 0");
session_start();
include $_SERVER['DOCUMENT_ROOT']."/Includes/object_one.php";
include $_SERVER['DOCUMENT_ROOT']."/Includes/object_two.php";
$fp= fopen('php://output', 'w');
foreach ($_SESSION['data'] as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
exit();
if it helps my array is in this format:
$data = array(dataset1(array, of, data), dataset2(array, of, data), dataset#(array, of, data));
EDIT: Session_Start doesn't seem to be causing the issue but the includes do.

It could be a header problem. If you print something before the header function (like a space from a file inclusion dued to a wrong php-tag closing), all headers doesn't works. Try to put ob_clean() before declaring headers and check if works.

Related

Export to CSV using fputcsv()

Im trying to make a CSV export from data entered in an array on my website. I was using this question to help me. I am getting the data that should be in the CSV echoed on my website but not exported to a file. This is the code that I took from the question:
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$filename\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($data as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
exit();
I dont exactly understand what the header() functions are doing. How would I get this to download to a file?
if it helps my array is in this format:
$data = array(dataset1(array, of, data), dataset2(array, of, data), dataset#(array, of, data));
EDIT:My $data array is in a session varible and the reason it wasnt downloading was because there I had session_start() and some includes at the top. Instead of downloading it would echo to the screen but if I remove this it downloads at the cost of there being no data to export. Anyone have a solution to this?
The header() function is sending HTTP headers to your browser with the respective values.
It then sends the CSV data to the output stream which the browser interprets as a downloadable file due to the headers.

headers already sent , export csv , can't download the file

im writing a basic script to download csv file based on database information,
in my dashboard/index.php i use GET and switch to include pages
so when i click on the link dashboard.php?link=export.php
i have a table with the all the data , there i have a link that i can download my csv file , my problem is that when i click to export.csv , i have an text output and not download file so i put those code :
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$filename}.csv");
header("Pragma: no-cache");
header("Expires: 0");
but always i see the content in text format and with an error
Warning: Cannot modify header information - headers already sent by (output started at /home/*/public_html/dev/dashboard/index.php:78) in /home/*/public_html/dev/dashboard/component/export.php on line 39
so i ask how can i resolve this issue , can i remove the header for the index in the export.php and set a new one also there to download the file or what extacly
maybe i need to change just in the export.php the Content-Type to be text/csv
but is alrady sent text/html .
please help to resolve this
thank you
As you can see, there is something already sent to output (printed) in your index.php file which is including your export.php file.
Make sure you are not printing anything before the headers. In some cases might be a space between the opening <?php tags or something little like that. btw mind that switch inclusion cases you have.
Other way is to try to use header_remove(); before the statements in export.php
Do not add anything before header in my case i was getting record from data base.
If you have function to download csv the add following header at top in the function like:
function exportCsv($date) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
.
.
.
.
}

PHP download CSV

Stuck on what is likely a silly problem and only posting after reading several related threads.
Have a page with a lot going on, one of the form options I'm trying to add is so the user can select to download array results in CSV. Problem is HTML header info is coming through in addition to the CSV data I want.
Code is:
function Array2Csv($result, $filename){
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' .$filename);
$output = fopen('php://output', 'w');
while($row = mysql_fetch_assoc($result)) {
fputcsv($output, $row,'|','"');
}
}
Problem is the result file includes BOTH undesired markup (headers and scripting references) in addition to the CSV itself. Desired output should only include the CSV data.
You have send the the header before any output was send. Disable view and layout.
See also http://php.net/manual/en/function.header.php

how to serve output as file without saving it on server

I'm serving some records from a MySQL database using PHP's fputcsv() by creating a file on the server, filling it, then linking to it on the next page.
This works and is great but as this could be sensitive data, I don't want a buch of files hanging about on the server when they were created for (probably) a one-time download.
So what I want to know is this: is there a way to create this file & serve it for download without actually writing a permanent file on the server?
For instance could I create a comma separated string instead of using fputcsv() and serve that with the right headers in an output buffer?
The obvious move is to delete the file but I need to wait until the client downloads it first so that makes it a little difficult to decide when to do it.
Any suggestions welcome
The code:
$fp = fopen($filename, 'w');
fputcsv($fp, array("Last Name", "First Name"));
foreach ($result as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
http://php.net/manual/en/function.fputcsv.php
fputcsv() is a fabulous little function, so I wouldn't abandon it.
Instead, I suggest you play around with PHP's built-in I/O Wrappers
You, can, for example, do this to "stream" your CSV data line-by-line (subject to various output buffers, but that's another story):
<?php
header('Content-type: text/csv; charset=UTF-8');
header('Content-disposition: attachment; filename=report.csv');
$fp = fopen('php://output','w');
foreach($arrays as $array) fputcsv($fp, $array);
That works great, but if something goes wrong, your users will have a broken download.
So, if you don't have too much data, you can just write to an in-memory stream, just swap out php://output with php://memory and move things around:
<?php
$fp = fopen('php://memory','rw');
// our generateData() function might throw an exception, in which case
// we want to fail gracefully, not send the user a broken/incomplete csv.
try {
while($row = generateData()) fputcsv($fp, $row);
}catch(\Exception $e){
// display a nice page to your user and exit/return
}
// SUCCESS! - so now we have CSV data in memory. Almost like we'd spooled it to a file
// on disk, but we didn't touch the disk.
//rewind our file handle
rewind($fp);
//send output
header('Content-type: text/csv; charset=UTF-8');
header('Content-disposition: attachment; filename=report.csv');
stream_get_contents($fp);
Rather than that, why not just have your page echo out a csv mime type and then echo out the file to the user?
It works a charm, the file is never created and passed as a one off to the client.
Something like this:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "col1,col2";
for($i=0; $i<25;$i++)
{
echo "key :".$i.", ".($i*$i)."\r\n";
}
You should be able to test that out as is and see how it works.
The added beauty is that most users will be directed to download the file rather than opening it, so the user doesn't even leave the page (most of the time).

Download headers somehow inserting 18 lines of whitespace

I am trying to serve up a dynamically generated csv file. For some reason when I get the file, there are 18 empty rows preceding the data. I don't have any space between the headers I define and the csv data I'm sending. If I write the data to a file on the server, it does not get these empty rows. However, if I write the file and then try to serve it to the user, the empty lines come back. So I'm wondering if perhaps I've messed up the headers, or if perhaps there is another issue I'm not thinking of:
function generate_csv($source_type, $include_unpublished = FALSE) {
// retrieve data from DB
....
// start up headers
$csv_name = "$source_type-$data_set-csv_" . date('Y-m-d') . '.csv';
header('Content-Type: text/x-comma-separated-values');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browser
header('Content-Disposition: attachment; filename="' . $csv_name . '"');
// send csv data
print $csv_data;
} //end function
Disclaimer: I asked this question at https://drupal.stackexchange.com/questions/27649/extra-empty-rows-when-serving-csv-file, but it dosn't seem to be drupal-specific and there weren't many ideas coming up over there..
Maybe this lines "hang" in an output buffer, that were started some time before. This way you can set headers without the good old "headers already sent"-error, but this content will be send to the browser when flushing the buffer anyway.
Try
ob_clean();
print $csv_data;
http://php.net/ob-clean
It must be problem with files that you are including. Every whitespace more than one newline after php closing tag ?> is sent to the browser.
Best solution is to get rid of this closing tags in every php file.
Other option will be to remove only unnecessary new lines from them or to bufer output and disregard it before serving file.

Categories