Saving Generated CSV to Server in Proper format as download - php

I've have been successful in exporting my database to csv as a downloadable file. However what I now need to do is instead of creating a straight .csv file that's downloaded I need it to just save to a folder called "csv" on the server. Here is my code for the current export. I need help in the saving it to server. I'm not saving the data correctly.
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('tax_class_id','_product_websites'));
// fetch the data
mysql_connect('localhost:3036', 'x', 'x');
mysql_select_db('lato');
$rows = mysql_query('SELECT taxclass,productwebsite FROM product');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
$filename = "data.csv"; // Trying to save file in server
file_put_contents("download/" . $filename, "$header\n$rows");

You need to change your last line to
$filename = "data.csv"; // Trying to save file in server
file_put_contents("download/" . $filename, $output);

Related

PHP Export to CSV file works on XAMPP but not Hostgator

this code works on my offline version in xampp and automatically downloads CSV file. But the same code doesn't work on my live website in Hostgator. Is there something that i should change? it just displays on the browser instead of automatically generating/downloading the csv file
$delimiter = ",";
$filename = "depot_".$direction. date('Y-m-d') . ".csv";
// Create a file pointer
$f = fopen('php://memory', 'w');
// Set column headers
$fields = array( 'Depot Ref','Container No', 'Container Type', 'Check-In Date', 'Storage');
fputcsv($f, $fields, $delimiter);
// Output each row of the data, format line as csv and write to file pointer
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$storage=getStorage($row["depotRef"]);
$lineData = array( $row["depotRef"], $row['containerNo'], $row['containerType'],
$row['checkIn'], $storage);
fputcsv($f, $lineData, $delimiter);
}
// Move back to beginning of file
fseek($f, 0);
// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
exit;

How to copy a php file to a csv file and download it?

I want to copy an entire php file into a csv file and download it, but the demo.csv file that I get is empty. Why am I getting an empty file?
The data in the php file is stored per line.
<?php
// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');
$handle = fopen("caldataprog.php", "r"); //fileurl
$lines = [];
if (($handle = fopen("caldataprog.php", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$lines[] = $data;
}
fclose($handle);
}
$fp = fopen('demo.csv', 'w');
foreach ($lines as $line) {
fputcsv($fp, $line);
}
fclose($fp);
?>
What I see is that you finally copy a file to other and don't flush this last.
<?php
$source = 'caldataprog.php'; // Presuming it contains raw CSV
$destination = 'demo.csv';
copy($source, $destination);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
readfile($destination); // Send file to user
If caldataprog.php generates CSV and you want to copy the result, you can do :
$source = 'http://yourwebsite.net/caldataprog.php';
$destination = 'demo.csv';
copy($source, $destination);
You are writing the output data to a file named demo.csv on your server, and you are downloading a file named demo.csv in your browser, but they are not the same file.
If you want to download the file in your browser, you need to have PHP output the file's contents.
You could do this using readfile, or by just using echo while you are reading the original input file (and never save the local demo.csv on the server's disk).

Print raw html to xls file in php

I am trying to create a xls file in php. And I am making a string in html format lets say <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table> and want to print in xls file as it is. but My problem is that when I try to print in xls file its getting render. but I want raw html string without rendered in xls file.
Here is my code:-
<?php
$file="demo.xls";
$test="<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header('Content-type: application/excel');
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>php
You can also use a service called DocRaptor which does html to excel conversion. http://docraptor.com/ , Multiple language supported
Or You can use the below code to download the file in Excel but first you have to download the PHPExcel class files and include like below .
require_once "excel/Classes/PHPExcel.php";
$objTpl = new PHPExcel();
$l=0;
$row_num = 1;
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setName('Calibri');
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
$objTpl->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objTpl->getActiveSheet()->duplicateStyle($objTpl->getActiveSheet()->getStyle('A1'), 'B1:Z1');
$objTpl->getActiveSheet()->getStyle('A1:Z1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// you can use loop over here remember to set $row_num = 2 if using loop and increment it inside $row_num++
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 1');
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 2');
$filename='some_file.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
exit; //done.. exiting!
There is a way by either writing html in file or comma separated text
With HTML
$xlsx_file = $pathinfo['dirname']."/".$pathinfo['filename'].".xlsx" ;
$fh = fopen($xlsx_file, 'w+');<br>
fwrite($fh, $table); // your table <br>
fclose($fh);<br>
with array or string of csv
$data = '"Name"t"City"t"Country"' . "n";<br>
$data .= '"Ashok"t"New Delhi"t"India"' . "n";<br>
$data .= '"Krishna"t"Bangalore"t"India"' . "n";<br>
$f = fopen('data.xls' , 'wb');<br>
fwrite($f , $data );<br>
fclose($f);<br>
this is temporary solution but if you want full set of options you go for PHP Excel as suggested by others

Use fputcsv create a .csv file and also update the page with table data

I am using fputcsv to create a .csv file and download it automatically for the user. This works great:
function create_csv($data, $not_valid, $csv_old_count, $file_name) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
fputcsv($fp, $line);
}
fclose($fp);
exit();
}
But, I would also like to update the page with a table that shows the data that was put into the csv file. When trying to do this by removing exit() and adding a loop to write the table, that data also get written to the csv file instead of writing to my page.
How can I create and download the .csv and also write some HTML to the page?
You can add the output to your foreach() -
foreach ( $data as $line ) {
fputcsv($fp, $line);
$newLines .= $line . "<br />"; // you'll have to figure out formatting
}
fclose($fp);
echo $newLines; // place this where you want to display the lines

Forcing generated CSV to download when run as cron on server

I'm trying to get an export to CSV script to download to the server when run as a cronjob but also still work via web.
When I run the script from web it forces a CSV to download which is great, however when I run it on the server (CentOS Server) it just echos the file contents instead.
I need it to download the file into the area defined in the cronjob.
//OK lets export
include("config.php");
$table = "data";
$filename = "Export_" . date("Y-m-d_H-i");
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $filename . ".csv");
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('artist', 'title', 'presenter', 'timeplayed'));
// fetch the data
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db('prs');
$rows = mysql_query('SELECT * FROM '.$table.' WHERE timeplayed >= NOW() - INTERVAL 24 HOUR ORDER BY id DESC');
if($rows === FALSE)
{
die(mysql_error());
}
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
Anyone with any other ideas?
See the manual
php://output is a write-only stream that allows you to write to the output buffer mechanism
in the same way as print and echo.
That really says it all.
So when you run this from a browser the standard output mechanism is send it to the browser as that is what echo or print would do. But in PHP CLI mode it sends the output to the terminal.
Answer is change this line from
$output = fopen('php://output', 'w');
to
$output = fopen($filename, 'w');
You then just have to decide if you are running through the browser or the CLI(cron job) and here is a suggestion
if ( php_sapi_name() !== 'cli' ) {
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $filename . ".csv");
readfile($filename);
}
You are going to have to check what your system reports using php_sapi_name() just to be sure you are testing for the right condition.

Categories