Trying to automatically open a dynamically generated CSV file from PHP script? - php

I'm successfully getting the desired output in console, but the browser isn't automatically downloading the CSV file.
header('Content-Type: application/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
$output = fopen('php://output', 'rb');
// output the column headings
fputcsv($output, array('Procedure Name', 'Totals'));
foreach ($rows as $row){
fputcsv($output, $row);
}
fopen($filename);
fclose($output);

A sample wich running in my browser:
$csv= '"Procedure Name", Totals'."\n";
$rows= array(
array('aaa', 'bbb'),
array('123', '456')
);
foreach ($rows as $row){
$csv .= implode(",",$row)."\n";
}
$filename= 'Totals Report for '.$name.' All-Time.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
die($csv);

Bah, this got unruly in the comments. I took it a step further and made it loop through the values too!
// Set headers
header('Content-Type: text/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
// Column titles
echo 'Procedure Name,Totals' . "\n"; // Don't forget the newlines!
// Data
foreach ($rows as $row) {
foreach ($row as $index => $value) {
echo $value;
if ($index < count($row) - 1) {
echo ',';
}
}
echo "\n";
}
You could also buffer it into a file so you can use fputcsv. That would work almost exactly as your current code, but at the end you'd have echo file_get_contents($the_buffer_file);
The main point is that all you need to do is output your data in CSV format, i.e. separate values by commas and a new line is a new row. It would also be smart to escape the values with quotation marks (not shown in my code).

Related

Multiple Error Messages after exporting excel from php

Error Message while opening the file
Second error message when trying to update the file...
Code in PHP
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
echo implode("\t", ["Username", "Order Number"]) . "\n";
echo implode("\t", ["wswswsw#s.com", "1234454542122232"]) . "\n";
exit();
?>
Am I missing anything?
This code may be able to assist you in finding a solution to your issue. If it doesn't work as expected, there may be other options that you can try.
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
// Generate the data for the file
$data = [
["Username", "Order Number"],
["wswswsw#s.com", "1234454542122232"]
];
// Use a loop to generate the rows of the file
foreach ($data as $row) {
// Use implode() to concatenate the values in the row into a single string
echo implode("\t", $row) . "\n";
}
exit();
?>

Create excel file without library

I using this code:
header( "Content-Type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=liste.xls");
echo "\xEF\xBB\xBF";
and I writing my SQL datas in a while loop like this:
echo "\n<table><tr><td>".$first[$post_a]."</td>\t<td>".$second[$post_a]."</td>\t<td>".$third[$post_a]."</td>\t</td></tr></table>";
When I try to open this created file, excel saying version and type are unmating even so I can open file after this warning on desktop but when I try to open on my phone file can't opening after warning.
You need to something like this here. Also ignore my logic in for-loop, may want to use your own.
$filename = "export_".date("m-d-Y_hia") . ".csv";
ob_end_clean();
$fp = fopen($filename,"w");
$is_header = true;
$no_meta_appnd = array('SKU','Name','Publish','Categories','Description');
foreach ($res as $index => $product){
$arr = array();
if($is_header){ // put all the header in array
foreach ($product as $index => $p){
if(in_array($index,$no_meta_appnd)){
array_push($arr,$index);
}else{
array_push($arr,"Meta: ".$index);
}
}
$is_header = false;
fputcsv($fp,$arr); // add headers
$arr = array(); // empty out array for first row
foreach ($product as $index => $p){
array_push($arr,$p);
}
fputcsv($fp,$arr); // add first row after header
}else{
foreach ($product as $index => $p){
array_push($arr,$p);
}
fputcsv($fp,$arr); // rest of the rows
}
}
//unserialize();
fclose($fp);
// download
// header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
header('Pragma: no-cache');
readfile($filename);
// deleting file
unlink($filename);
exit();

Array to csv download in PHP

I am trying to turn my array in PHP into a csv to download.
Currently the array looks something like this
Array[0] = "Name,age,ID"
Array[1] = "Alex,26,1"
Array[2] = "Ryan,12,2"
Array[3] = "Steph,56,7"
etc
I was unsure how to make this download as a csv, where each array position is its own line is csv obviously.
I set the headers to the following :
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
then I tried to echo each element of the array, hoping this would work. as follows:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
foreach ($lines as &$line) {
echo $line;
}
Where $lines was my array.
However it did all one line in the csv. Is there a way I can turn this array to print properly in csv?
You have to add a newline
echo $line . "\n";
Even better
echo $line . PHP_EOL; //constant for correct line-ending depending on OS.
One of solution is fputcsv function.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
$output = fopen('php://output', 'w');
foreach ($lines as $line) {
$row = explode(',', $line);
fputcsv($output, $row);
}
fclose($output);

Why my CSV file was start filling from the 2nd line?

I am exporting MySQL data successfully to a csv file. But in the csv file first line was empty and data starts from 2nd line. Below is my code.
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w+');
fputcsv($output, array('Order Type','Order Number','EAN','Article #'),$delimiter);
sql query
<?php
$lineData = array();
$query = "my select query";
$res = mysqli_query($mysqliConn,$query);
while($result= mysqli_fetch_assoc($res))
{
$lineData[] = $result;
fputcsv($output, $lineData, $delimiter);
unset($lineData);
}
Data was exporting successfully to csv but it was starting from 2nd line, any help would be greatly appreciated.
EDIT
<?php
//header info for browser
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w');
fputcsv($output, array('Order Type','Order Number','EAN','Article #','Title','Amazon Price','ERP Price','Requested Quantity','Dispatch Quantity','Rejected Quantity','Cancelled Quantity','Delivery Date','Status','EDD','LDD','Dispatch Center','Order Received','Price Status','Country'),$delimiter);
?>
I just removed all my mysql related query and only using the above one.

instead of generating .xls file i am getting .php file on server side

I'm using following headers to generate excel file from database MySQL using PHP
header("Content-type: application/octet-stream");
header("Content-Type: application/vnd-ms-excel");
header("Content-disposition: attachments;filename=xxx.xls");
in localhost the output is xxx.xls which is correct file but in the server side i am getting xxx.php file (i am using a cpanel account for ftp)
guys please help me with a solution
simply use
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
Simply you can use the following php code.
You have to give an array with key value pair
$data = array("Name"=> "foo", "age" => 25);
$filename = "My File Name" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
foreach ($row as $value){
echo $value;
echo "\t";
}
echo "\n";
}
exit;

Categories