I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.
Here's my code:
<?php
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);
?>
$stories is my array created from the MySQL query.
Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?
final working code:
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
You can call model CSV() from your controller as
$this->load->model('Users_model');
$this->Users_model->csv();
and in the model
function csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("SELECT * FROM Users");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
}
Your File will start downloading
I can't tell what headers are set from the Codeigniter force_download() function sets. If it is indeed going to the screen I would suspect the necessary headers are missing. You can add the below headers to your code to set correct csv dowload headers (The cache control will ensure fresh data download each time:
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
i am use this and its work
header('Content-Type: text/csv; charset=utf-8');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
header('Last-Modified: ' . date('D M j G:i:s T Y'));
$outss = fopen("php://output", "w");
$this->db->order_by('ID', 'DESC');
$query = $this->db->get('urls');
foreach ($query->result_array() as $rows) {
fputcsv($outss, $rows);
}
fclose($outss);
return;
If you are trying to generate reports in csv format then it will quite easy with codeigniter.
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.
Here we have sample result set from MySQL and want to export in CSV file.
Step 1: Get MySql data in key value pair.
$data = array(
'0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
Step 2: PHP code to get options type and force to browser download file instead of display.
if(isset($_POST["ExportType"]))
{
switch($_POST["ExportType"])
{
case "export-to-csv" :
// Submission from
$filename = $_POST["ExportType"] . ".csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportCSVFile($data);
//$_POST["ExportType"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
}
function ExportCSVFile($records) {
// create a file pointer connected to the output stream
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// output the column headings
fputcsv($fh, array_keys($row));
$heading = true;
}
// loop over the rows, outputting them
fputcsv($fh, array_values($row));
}
fclose($fh);
}
Step 3: Define html layout for display data in table and button to fire export-to-csv action.
<div>Export to csv</div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="" class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Status</th>
<th>Priority</th>
<th>Salary</th>
</tr>
<tbody>
<?php foreach($data as $row):?>
<tr>
<td><?php echo $row ['Name']?></td>
<td><?php echo $row ['Status']?></td>
<td><?php echo $row ['Priority']?></td>
<td><?php echo $row ['Salary']?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Step 3: Now we will use jQuery code to get click event.
<script type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
case 'export-to-csv' :
$('#hidden-type').val(target);
//alert($('#hidden-type').val());
$('#export-form').submit();
$('#hidden-type').val('');
break
}
});
});
</script>
Related
I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);
I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.
I'm working on a project, that requires exporting data from MYSQL DB depending on the multiple conditions. I am referring this:
This is my source code:
public function exportExcelData($records)
{
$heading = false;
if (!empty($records))
foreach ($records as $row) {
if (!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", ($row)) . "\n";
}
}
public function fetchDataFromTable()
{
$query =$this->db->get('one_piece_characters'); // fetch Data from table
$allData = $query->result_array(); // this will return all data into array
$dataToExports = [];
foreach ($allData as $data) {
$arrangeData['Charater Name'] = $data['name'];
$arrangeData['Charater Profile'] = $data['profile'];
$arrangeData['Charater Desc'] = $data['description'];
$dataToExports[] = $arrangeData;
}
// set header
$filename = "dataToExport.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$this->exportExcelData($dataToExports);
}
If I use it without any where clause, it is giving entire table.
If i use only single where clause, it works good.
Bur, if I use multiple where conditions. it gives me a blank excel sheet.
Does anyone have any idea regarding how to make it work with multiple where conditions?
Try using this code on your model file:
function createcsv(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM YourTable"; //USE HERE YOUR QUERY
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
// ecport contect list in csv ,
public function cnt_explode(){
$csvData[] =array( "Name", "Email Id","Mobile No.","Event", "City","location","No of guest","Event Date","Budget",
"Venue Type","Food","Drink","Description","Date");
$data = $this->contact_model->get_contact(NULL);
foreach($data as $cnt){
$csvData[]=array(
$cnt->name ,$cnt->email, $cnt->mobile_no, $cnt->event, $cnt->city, $cnt->location, $cnt->no_guest,$cnt->event_date,$cnt->budget, $cnt->venue_type,
$cnt->food, $cnt->drink, $cnt->description,$cnt->created_on,
);
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=venuexpo_".time().".csv");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
array_walk($csvData, function($row) use ($df) {
fputcsv($df, $row);
});
fclose($df);
}
///------------ downlode csv done --------------
I am facing with strange problem while exporting my csv file on safari it is just displaying on browser instead of downloading .While same code is working with Firefox and Crome.I have searched but nothing is working for me. Please help. Here is my code-
<?php
ob_clean();
ob_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
function exportData() {
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Market ID', 'Market Name', 'Suburb', 'State', 'Start Time', 'End Time', 'Status',"~"));
include "database.php";
$dbquery = #$_POST['query'];
$queryAllUser = $dbquery;
$resultAllUser = mysql_query($queryAllUser);
$countAllUser = mysql_num_rows($resultAllUser);
if($countAllUser > 0)
{
while($rowMarketId= mysql_fetch_assoc($resultAllUser))
{
$marketId = $rowMarketId['mrkt_id'];
$isCancel = $rowMarketId['is_cancel'];
$openning_tim = $rowMarketId['openning_time'];
$closing_tim = $rowMarketId['closing_time'];
$suburb = $rowMarketId['suburb'];
$name = $rowMarketId['name'];
$state = $rowMarketId['state'];
if($isCancel == 0)
{
$status_type = "Open";
}
else
{
$status_type = "Close";
}
$val = array();
$val[] = $marketId;
$val[] = $name;
$val[] = $suburb;
$val[] = $state;
$val[] = $openning_tim;
$val[] = $closing_tim;
$val[] = $status_type;
$val[] = "~";
fputcsv($fp, $val);
}
}
}
exportData();
?>
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' .urlencode(basename($filename)));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
Try With this Headers........ This should Work..
Hello I am trying to grab all the emails from the database, then output them into a text (comma separated) file. Here is what I have done but does not work:
public function get_textfile() {
$emails = Staff::get('email');
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.txt"');
$stream = fopen("php://output", 'w');
foreach($emails as $email) {
fputcsv($stream, $email, ',');
}
fclose($outstream);
}
return (something)?
getting this: Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
This is my route:
Route::get('textfile', array('as' => 'textfile','uses' => 'admin#textfile'));
try file_put_contents($filename, implode(',', Staff::get('email')));
Collect all of your data into a string and then output it like this:
$data = '';
foreach ($emails as $email)
{
// If you want 1 email per line
$data .= '"'.$email.'"'.PHP_EOL;
// If you want all emails on 1 line
$data .= '"'.$email.'",';
}
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=My Cool File.csv');
header('Pragma: no-cache');
header('Expires: 0');
echo $data;
need to generate a txt file with the following output html code
<?php
function video() {
$video = 'BYN-DEM7Mzw';
echo '<script type="text/javascript">
function youtubeFeedCallback( data ){
document.writeln( data.entry[ "media$group" ][ "media$description" ].$t.replace( /\n/g, "<br/>" ) + "<br/>" ); }
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/'.$video.'?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>';
}
ob_start();
video();
$output = ob_get_clean();
$desc = $output;
$video = 'BYN-DEM7Mzw';
$arq = $video.".txt";
$f = fopen($arq, "w+");
fclose;
$f = fopen($arq, "a+");
$content = "";
if(filesize($arq) > 0)
$content = fread($f, filesize($arq));
fwrite($f, $desc);
fclose($f);
?>
the problem that the file is saving up my script and not the output html
I think you should be using the right headers and the correct mime in it.
For example
header('Content-Description: File Transfer');
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
if ($file != '')
{
echo file_get_contents($file);
}