This is my current code which pulls all data into a single column. I would like it
to pull data into its own column. Thanks for any help
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
foreach ($query as $k=>$v) {
$_csv_data= $v["email"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["first_name"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["business"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["phone_no"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["shipping_address"]. "\n";
fwrite( $fp, $_csv_data );
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
This is my first post on here and I've found all the info here very informative. Thanks for all you do.
EDIT:
Here is the current code with the syntax error
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
fputcsv($fp, $data);
unset($data);
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
For CSVs, instead of fwrite, you can use fputcsv, you just pass it an array of columns to insert in the row.
$array = array('column one contents', 'column two contents');
fputcsv($fp, $array);
I would suggest looking into fputcsv.
php manual
It looks like your code was looping through all the data, printing out the email. Then looping again and printing out the first_name... I haven't tested it, but this uses fputcsv to write the file - I changed only those parts of the code.
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
$lines[] = $data; // add the row of data to $lines
unset($data);
}
fputcsv($fp, $lines);
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
Related
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 new in laravel, when I hit my code then it's given response in browser like
output:
ID,"Event Name"
1,"test event"
3,"test test 1"
please see my below code and guide me =>
$events = Events::all()->toArray();
$event_set = array();
//echo '<pre>'; print_r($events); die;
$i =0;
foreach ($events as $event)
{
$record['id'] = $event['id'];
$record['event_name'] = $event['event_name'];
$event_set[$i] = $record;
$i++;
}
//echo '<pre>'; print_r($event_set); die('test');
$filename = "events.csv";
$header = ['ID', 'Event Name'];
$export_data = $this->getDataCsv($event_set, $header);
return response($export_data)
->header('Content-Type','application/csv')
->header('Content-Disposition', 'attachment; filename="'.$filename.'"')
->header('Pragma','no-cache')
->header('Expires','0');
function getDataCsv($data, $headers, $delimiter = ',', $enclosure = '"') {
$filename = "php://temp";
$fp = fopen($filename, 'w');
fputcsv($fp, $headers, $delimiter, $enclosure);
if(count($data)>0){
foreach ($data as $key => $value) {
fputcsv($fp, $value, $delimiter, $enclosure);
}
}
rewind($fp);
$csvdata = fread($fp, 1048576);
fclose($fp);
return rtrim($csvdata, "\n");
}
please suggest me, what I doing wrong ?
use this function to generate and download CSV file
pass data as:
$data = [
['ID', 'Event Name', 'test event'], // this is going to be header for the csv file
[1, 'xyz', 'aadfas'],
[2, 'abc', 'jljljl'],
];
and call this function
public function arrayToCSVDonwload($data, $fileName = null, $delimiter = ",")
{
$fileName = $fileName ? $fileName . '.csv' : microtime(true) . ".csv";
header("Content-Type: application/csv");
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$fileName");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row, $delimiter);
}
fclose($output);
exit;
}
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 have been creating a CSV by using array of data, currently it returns an error if a CSV already exists in the same location.
therefore is there a possibility where i could let it create another in the same location.
example : if theres a csv called report.csv to create a new one with auto generated name like report(1).csv
code
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary");
fclose($fp);
working example finally.. thank you for your ideas
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
if(file_exists($basePath) == false){
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}
else{
$time_start = time();
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report"."#".$time_start.".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}
I want to open a csv file named csv.csv with PHP, then add new rows in this file, and finally download the news csv.
The content of csc.csv is:
name, town
name1, town1
name2, town2
name3, town3
name4, town4
and I want to add these rows:
name5, town5
name6, town6
I made this PHP code but it doesn't work:
<?php
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[] = array(print_r(fgetcsv($file)));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>
Here is your working code.
<?php
$file = fopen("csv.csv","a+");
$list = array();
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
foreach ($list as $fields) {
fputcsv($file, $fields,',');
}
fclose($file);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv_".time().".csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
UPDATE 1 :
for creating new file without editing existing one.
<?php
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);
}
?>