Issue on opening, editing and downloading a .csv file on PHP - 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);
}
?>

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

PHP simple csv export is not work with array in Wordpress Plugin

I'm tring to export csv file from the PHP array in wordpress plugin.
However when I put die inside the foreach the CSV file created with the first elements of array. otherwise CSV file not generate.
Array :
Array
(
[0] => Array
(
[fname] => test name 1
[lname] => lname 2
)
[1] => Array
(
[fname] => test name 2
[lname] => lname
)
)
Code :
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=loyalty.csv');
$filename = "loyalty.csv";
$handle = fopen('php://output', 'w');
fputcsv($handle, array('First Name','last Name'));
foreach($loUsers as $row) {
fputcsv($handle, $row);
//die;
}
fclose($handle);
When the die is not commenting nothing will happen but if I put but csv file created with first element.
Seems the code is correct and can't find the issue.
Thanks
Try this:
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=User_Sample.csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
$data = array(
array('User Type', 'User Name', 'Category', 'Mobile Number'),
array('I', 'Anuj Kumar', 'Building Construction', '8500000001'),
array('I', 'Arvind Kumar', 'Carpentary', '8500000002'),
array('I', 'Mridul Ohja', 'Civil Engineering', '8500000003'),
array('I', 'Naman Kumar', 'Electrical', '8500000004'),
array('I', 'Sumati', 'Faucets', '8500000005'),
array('I', 'Anjum', 'Flooring Tiles / Marbles', '8500000006'),
array('I', 'Rajat', 'Painting', '8500000007'),
array('C', 'Arvind', 'Plumbing', '8500000008'),
array('C', 'Rohit', 'Sanitaryware', '8500000009'),
array('C', 'Gaurav', 'Soil Test Analyst', '8500000010')
);
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row); // here you can change delimiter/enclosure
}
fclose($output);
It works for me.
Check this out its easy:
<?php
session_start();
include_once('includes/config.php');
$filename = "testing-exports.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$insquery = "SELECT username FROM r_institution where status=1";
//$exportstmt = $conn->query($insquery);
$insresults = $conn->query($insquery);
//$insresults = mysqli_fetch_assoc($exportstmt);
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$content = array();
$title = array("Institution Emails");
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
?>

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

create CSV in a different name if file already exists

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

Categories