With PHP I'm opening a .csv file, I'm adding som rows in it then I'm downloading the new .csv file.
the code I'm using is:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("csv.csv","r");
$list = array();
while(! feof($file))
{
$list[] = (fgetcsv($file));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
$list = array_filter($list);
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
My issue is the other PHP code in the page don't generate, and only the .csv file is being download.
for exemple if I'm adding:
echo "test";
it won't be display and only csv.csv will be downloaded
How can I display my "echo test;" ?
With the headers you are telling the browser to download a CSV, there is no where to output your echo.
You could make a page with the information you want to show that has an iframe with the csv code in it.
Related
I am a beginner student of PHP and i am doing some practice by coding a script to generate a CSV file.
Once that the csv file is generated , the format is correct as I've expected :
See the attached :
But if i add the download option the csv is generated wrongly with all the PHP page (i can see all the code)
Here the picture of the wrong csv
Could you help me to find the issue ?
Here the code :
<?php
include("db.php");
session_start();
$sql = "SELECT isocode FROM test_geo ORDER BY isocode";
$result_csv = mysqli_query($conn, $sql);
//facebook csv creation //
$filename = 'test.csv';
$fp = fopen($filename, 'w');
$headers = ['key', 'country'];
fputcsv($fp, $headers);
foreach ($result_csv as $key => $id) {
$new = array_push($id, "country");
fputcsv($fp, $id);
var_dump($id);
}
fclose($fp);
?>
Try this
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
foreach ($new as $row) {
fputcsv($outputt, $row);
}
fclose($outputt);
exit();
I believe you put the header statements at the top of your script, so the download data includes the HTML codes too (like below...)
<!DOCTYPE html><html lang="en"><meta charset=...... >
You may use ob_flush() and set header (at the appropriate position of the code) so that the file will be correctly downloaded as csv when it is generated.
Here is the code:
<?php
session_start();
include("db.php");
$sql = "SELECT isocode FROM test_geo ORDER BY isocode";
$result_csv = mysqli_query($conn, $sql);
$data=array();
while($row = mysqli_fetch_array($result_csv, MYSQLI_ASSOC)) {
$ok=$row["isocode"] . "," . "Country";
array_push($data ,$ok);
}
ob_flush();
$filename="ok1.csv";
$csvData = join("\n", $data);
header('Content-Disposition: attachment; filename="'.$filename.'";');
header('Content-Type: application/csv; charset=UTF-8');
die($csvData);
?>
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();
I am trying to download a query as a .csv on a PHP web page, which has include_once ($_SERVER['DOCUMENT_ROOT'].'header.php'); at the top. When I use the PHP header() function to download it, the .csv file contains the html code from header.php followed by the .csv data. How do I get the .csv without the html (only the query data)?
For downloading I use:
$query_file_name = "App_data.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$query_file_name");
$query_file = fopen("php://temp", "w");
// write file
$row = $results->fetch_assoc();
fputcsv($query_file, array_keys($row)); // csv head
fputcsv($query_file, $row); // first line
while($row = $results->fetch_assoc()) {
fputcsv($query_file, $row);
}
fclose($query_file);
I realize I could trim the top of the file, but I do not know how to catch this before the file downloads. Optimally, I would only like to have the html from header.php not included at all.
You need to add a condition to skip Html Code in header.php when you are calling from csv file. I hope it' will work. please refer below code.
$fromCsv = true;
require_once 'header.php';
ob_start();
$query_file_name = "App_data.csv";
$query_file = fopen("php://output", "w");
// write file
$row = $results->fetch_assoc();
fputcsv($query_file, array_keys($row)); // csv head
fputcsv($query_file, $row); // first line
while($row = $results->fetch_assoc()) {
fputcsv($query_file, $row, ",");
}
header('Content-type: application/csv');
header('Content-Disposition: attachment;filename="' . $query_file_name . '.csv"');
header('Cache-Control: max-age=0');
header("Expires: 0");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
fpassthru($query_file);
fclose($query_file);
exit;
in header.php, all html code move to if condition
if (!$fromCsv)
{
//move all html code here
}
I ended up trying a question I found that previously didn't work. After adding ob_clean() to it, it works. My code ended up being
ob_end_clean();
ob_clean();
$query_file_name = "FabApp_data.csv";
$query_file = fopen("php://output", "w");
// write file
$row = $results->fetch_assoc();
fputcsv($query_file, array_keys($row));
fputcsv($query_file, $row);
while($row = $results->fetch_assoc()) {
fputcsv($query_file, $row, ",");
}
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=$query_file_name");
exit();
I want to generate a .csv file then download it with AJAX
Insite csv.php I have this code:
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("th.csv","r");
$list = array();
while(! feof($file))
{
$list[] = (fgetcsv($file));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
$list = array_filter($list);
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>
so when I'm going to csv.php it makes me download the csv file.
Then inside test.php I have this jQuery code:
$(document).on('click', '#listCSV', function() {
var el = $(this),
csv = el.attr('csv');
$.ajax({
type: 'POST',
url: 'csv.php',
data: {
listCSV: csv
},
success: function(data, textStatus, jqXHR) {
el.html($(data));
}
});
});
But when I'm clicking on #listCSV nothing happens, nothing is being downloaded
Any idea how can I download the csv file when clicking on #listCSV?
generate the csv file and store it in a directory.
say:
root/csv/file_timestamp.csv
when the file is generated just use the file_timestamp.csv location on you're link.
so if your file_timestamp.csv is can be accessed via
http://project/csv/file_timestamp.csv
then just link it to a regular link:
<a href="http://project/csv/file_timestamp.csv"/>download csv</a>
Note:
if you're not expecting multiple users to generate csv files then just make a temporary file then you can set the link as static. if not just delete every file in the csv folder every 3mins
You need to change header information to output it as download :
$out = fopen("php://output", 'w');
$emails = array();
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="'.$this->filename.'.csv"');
foreach($contacts as $adr) $emails[] = $adr->getEmail();
fputcsv($out, $emails);
fclose($out);
exit;
I have a Wordpress theme template file in use by a page. The template queries the db for an array and then attempts to output the result to a csv file. No output to the browser is expected. Here is code:
/***
* Output an array to a CSV file
*/
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
$name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "w");
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}
The file is written to the user's downloads directory as expected, but it is empty. I've debugged to verify there is a result of 117 elements. The loop above is executing. It's as though the output buffer is not being flushed or is being cleared by Wordpress.
Could you try to use :
$outstream = fopen("php://output", "a");
instead of :
$outstream = fopen("php://output", "w");