create CSV in a different name if file already exists - php

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,',');
}
}

Related

didn't download .csv in laravel (php)?

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;
}

CodeIgniter: Export data from database into excel and download

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 --------------

Pull customer data into all columns in a csv file

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!";
}
?>

Issue on opening, editing and downloading a .csv file on PHP

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);
}
?>

How to fix error font UTF8 in file csv when export file csv in php

I export csv in php as:
$fp = fopen($filename, 'w');
foreach ($list as $fields) {
if(!empty($fields))
fputcsv($fp, $fields);
else
fputcsv($fp, ' ');
}
$fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8");
fclose($fp);
When i open csv, font UTF_8 is error.
Ex: 防本部コー show in file csv: æ¶ˆé˜²æœ¬éƒ¨ă‚³ăƒ¼ăƒ‰
Can I help you? Thanks
This has been discussed here:
How can I output a UTF-8 CSV in PHP that Excel will read properly?
You might also want to check your CSV in an alternative text editor to rule out the editor.
$fp is a pointer resource to a file. It is not a string, you cannot do this:
$fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8");
To write UTF-16 data to the file, you need to convert it before writing it, not after the fact:
$fp = fopen($filename, 'w');
fwrite($fp, chr(255).chr(254));
foreach ($list as $fields) {
foreach ($fields as &$field) {
$field = mb_convert_encoding($field, 'UTF-16LE', 'UTF-8');
}
fputcsv($fp, $fields);
}
fclose($fp);
Don't know if this actually outputs the data you need, but it fixes the obvious error.
Try this function will work:
public static function exportCSVFile($data = array(), $headers = array(), $delimiter = ",", $csvfilename = "CSVFile") {
ob_clean();
ob_start();
$csvfilename = $csvfilename . "_" . date("Y_m_d_h_i_s") . ".csv";
$file_handler = fopen("php://output", 'w');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/csv");
//header( "Content-Type: application/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename={$csvfilename}");
header("Content-Transfer-Encoding: binary");
foreach ($data as $fields) {
$_str = implode($delimiter, $fields);
$fields = explode($delimiter, utf8_decode($_str));
fputcsv($file_handler, $fields, $delimiter, $enclosure = '"');
}
fclose($file_handler);
ob_flush();
exit();
}

Categories