writing header into csv using php - php

i have a requirement where i am logging each page visit and activities into csv log file. how can i write so that the header should be written for the first time only not every time.
fputcsv($fh1, array(date,id1,page,id2,request,ip));
fputcsv($fh1, array($date,$mid,$page,$aid,$request,$ip));
The first array should be written once only for a particular date log file. Please Suggest.

You're going to kick yourself when you see this ...
if (!file_exists('log.csv'))
{
// Make the file & Write the header
}
// Write the log entry.

I hope you are trying to arrange the record with header when you download CSV. If YES then please have a look on this example below, where I am showing it in small example which works in Drupal-
<?php
function getUsersDetails(){
$csv_output = '';
$all_users_entry = db_query("SELECT * FROM users");
while($users = db_fetch_object($all_users_entry)){//suppose these fname,lname etc are column name of your table.
$fname = $users->fname;
$lname = $users->lname;
$date = $users->joining_date;
$role = $users->role;
$location = $users->location;
$csv_output .= "\"".$fname."\"".","."\"".$lname ."\"".","."\"".$date."\"".","."\"".$role."\"".","."\"".$location."\""."\r";
}
return $csv_output;
}
function download_details(){
$csv_output = '';
$csv_output .= "First Name,Last name,Member Since,Role,Place\n";
$csv_output .= getUsersDetails();
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="Usera_Details.csv"');
print $csv_output;
exit;
}
?>
Now you can call this function download_details() from any place and you will have users table details in the downloaded CSV

Related

creating multiple csv files from php loop

Im trying to create a loop that when executed it created multiple csv files and downloads them. This is my code:
session_start();
require '../connect.php'; //connect.php has connection info for my database
// and uses the variable $connect
$sqldept = "SELECT department_name from department;";
$departments = mysqli_query($connect, $sqldept);
while ($department = mysqli_fetch_array($departments)) {
$department = $department[0];
header('Content-Type: text/csv; charset=utf-8');
header("Content-Transfer-Encoding: UTF-8");
header('Content-Disposition: attachment; filename=summary-' . $department . '.csv');
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
$date = date("Y-m-d", strtotime("-28 days" . date("Y-m-d")));
$edate = date("Y-m-d");
$startdate = "(time.dateadded BETWEEN '$date' AND '$edate') AND";
$department = " and department_name = '$department'";
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
$sql2 = "SELECT time.id as timeid, time.staff_id, SUM(time.timein), COUNT(NULLIF(time.reasonforabsence,'')) AS count_reasonforabsence, GROUP_CONCAT(CONCAT(NULLIF(time.reasonforabsence,''),' ', date_format(time.dateadded, '%d-%m-%Y'),' ')) AS reasonforabsence, time.dateadded, staff.id AS staffid, department.id AS departmentid, department.department_name, staff.staff_name, staff.department_id, SUM(staff.workhoursperday), staff.payrollnum FROM time, staff, department WHERE $startdate staff.id = time.staff_id AND staff.department_id = department.id $department $staffsearch GROUP BY staff.id ORDER BY `time`.`dateadded` ASC;";
// output headers so that the file is downloaded rather than displayed
fputcsv($output, array(
'Payroll Number',
'Name',
'Department',
'Hours Worked',
'Days Absent',
'Overtime',
'Reasons for Absence'
));
$rows = mysqli_query($connect, $sql2);
while ($rowcsv = mysqli_fetch_assoc($rows)) {
$reasonforabsence = $rowcsv['reasonforabsence'];
//$reasonforabsence = explode( ',', $rowcsv['reasonforabsence'] );
$overtime = 0;
if (empty($rowcsv['SUM(time.timein)']) == true) {
$rowcsv['SUM(time.timein)'] = 0;
}
;
if ($rowcsv['SUM(time.timein)'] > $rowcsv['SUM(staff.workhoursperday)']) {
$overtime = $rowcsv['SUM(time.timein)'] - $rowcsv['SUM(staff.workhoursperday)'];
}
;
fputcsv($output, array(
$rowcsv['payrollnum'],
$rowcsv['staff_name'],
$rowcsv['department_name'],
$rowcsv['SUM(time.timein)'],
$rowcsv['count_reasonforabsence'],
$overtime,
$reasonforabsence
));
};
readfile("php://output");
fclose($output);
};
Currently the loop created 1 CSV with a new header and the department details below it like this
I want the loop to create a new CSV for each department but its just not working for me. Any help is appreciated.
Thanks
Unfortunately you can't, 1 PHP Request results in one file, and there isn't really a way around this. You can, however, try to download them all as a ZIP file. Take a look at this question f.e.
The below are some workaround ideas, which might be useful in certain scenarios (and might be dangerous in other scenarios). Use under your own risk!
Workaround A: Loop by redirect
Output a single file normally
Do a redirect to same url that's creating the CSV file in step#1, but append a GET flag to that, like http://www.example.net/output_csv?i=1
Make sure to add a loop-breaker in step#1, like if($i==10) { exit; }
Workaround B: Loop by cronjob
Output a single file normally
Make 2nd file output be handled by a separate cronjob call.
Make sure to add a loop-breaker in step#1, like if($mycron==10) { exit; }
You can not do this by for loop.
However, You can make a php file which can do your purpose.
<a onclick="getcsv()" href="php_file_location.php?table_name=test"> Download </a>
<script>
function getcsv() {
window.open(php_file_location);
}
</script>
I was in the same problem as mentioned. But in my case I was not trying to download multiple CSVs but I was uploading it to sFTP server. While creating the file instead of using
$output = fopen('php://output', 'w');
I used
$output = fopen($path_and_name, 'w');
where $path_and_name = $path_to_sftp_folder.'/'.$file_name;
after the execution the correct file was uploaded to there respective folders correctly the way I wanted it to be. But yes the wrong file was also downloaded with same issue as sent above.
So if you are looking for uploading files on a server it can be done(even if they all have same name).

exporting MYSQL fectched row into csv in php

Following is a part of my php program which is written to fetch rows from mysql table from input IDs. But I wanted to get the result directly to '.csv' file. I know php has built in function for that, but I could not include it effectively. So can anyone give a direction for export to csv using advanced php function?
$file = fopen("fetched.csv","w");
for($i=0;$i<=$len;$i++)
{
$lo = $locus[$i];
mysqli_select_db($conn,"microarray");
$query = mysqli_query("SELECT * FROM anatomy WHERE locus_id = "$lo"");
while ($row = mysqli_fetch_row($query))
{
}
}
You don't necessarily need an "advanced php function". A csv file is just a sequence of comma separated columns. Try this out.
function addRowToCsv(& $csvString, $cols) {
$csvString = implode(',', $cols) . PHP_EOL;
}
$csvString = '';
$first = true;
while ($row = mysqli_fetch_assoc($query)) {
if ($first === true) {
$first = false;
addRowToCsv($csvString, array_keys($row));
}
addRowToCsv($csvString, $row);
}
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
Notice that the first argument to addRowToCsv is passed by reference. This is not required and you could easily use a return value, but this is just how I would do it.
-- Edit --
I just noticed you are saving the output to a file rather than serving it as a download. If that is what you want to do then use the above but replace
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
With..
file_put_contents('MyCsvFile.csv', $csvString);

Downloaded .csv file contains HTML tags as text

I want to download a .csv file through link.For that a Download link is defined in a template file.
To generate .csv file I have written a piece of code as follows.
public function loadPartnerApplicantData() {
$inboundBo = BoFactory::getInboundHttpRequestBo();
$fileType = $inboundBo->getSanitizedGetParam('f');
$formId = $inboundBo->getSanitizedGetParam('fid');
ServiceFactory::getFormService()->loadFormDetails($formId);
$dbTable = BoFactory::getFormBo()->getFormDbTable($formId);
$formName = slugify(BoFactory::getFormBo()->getFormName());
$fileName = $formName . "." . time();
$fieldMasterSqlQuery = "SELECT field_name,field_label FROM" . FORM_FIELDS_MASTER_v2 . "where form_id='$formId' order by serial_no";
$fieldMasterSqlQueryStatus = mysql_query(mysql_fetch_assoc($fieldMasterSqlQuery));
$csvHeader = "";
$fieldNameArray = array();
foreach ($fieldMasterSqlQueryStatus as $key => $value) {
if ($value['field_name'] == 'declaration' || $value['field_name'] == 'docPicture') {
continue;
}
$csvHeader.= "\"{$value['field_label']}\";";
$fieldNameArray[] = $value['field_name'];
}
$queryString = implode(",", $fieldNameArray);
$dbTableSqlQuery = "SELECT $queryString FROM `$dbTable`";
$dbTableSqlQueryStaus = mysql_query(mysql_fetch_assoc($dbTableSqlQuery));
ef_clearBuffer();
// To generate csv
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$fileName.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo($csvHeader);
foreach ($dbTableSqlQueryStaus as $applicantData) {
echo "\n";
foreach ($fieldNameArray as $fieldName) {
echo "\"$applicantData[$fieldName]\";";
}
echo "\n";
}
}
And the required .csv is generated .
But at the end of .csv file HTML tags of the browser is getting displayed. which should not be there.
Please suggest me to remove the html content from the generated .csv file.
Thanks in advance.
Since your function handles the request till the end (i.e., delivers all data), and you don't want the framework (whichever you're using) to continue processing, add
exit(0);
as last line of your function. That will halt the processing after the content is delivered and prevent the framework/environment from sending additional data.
Maybe you already had some echo commands before the header manipulation, then the .csv file which you want to download will contains all strings you have written before.

send an email exported cvs file php mysql

I am trying to send email exported csv file. However, when i click the link, have a pop-up to download a CVS with the record from MySQL. how can i send an email this csv file to spesific email adress ? thanks a lot for help and ideas.
best regards.
Here is my code
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");
$resultstr = array();
foreach ($selectionlist as $result)
$resultstr[] = $result;
$ww=implode(",",$resultstr);
function escape_csv_value($value) {
$value = str_replace('"', '""', $value); // First off escape all " and make them ""
if(preg_match('/,/', $value) or preg_match("/\n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines
return '"'.$value.'"'; // If I have new lines or commas escape them
} else {
return $value; // If no new lines or commas just return the value
}
}
$sql = mysql_query("SELECT * FROM article
WHERE idArticle in ($ww) ORDER BY idArticle DESC"); // Start our query of the database
$numberFields = mysql_num_fields($sql) or die('MySql Error' . mysql_error());; // Find out how many fields we are fetching
if($numberFields) { // Check if we need to output anything
for($i=0; $i<$numberFields; $i++) {
$keys[] = mysql_field_name($sql, $i); // Create array of the names for the loop of data below
$col_head[] = escape_csv_value(mysql_field_name($sql, $i)); // Create and escape the headers for each column, this is the field name in the database
}
$col_headers = join(',', $col_head)."\n"; // Make our first row in the CSV
$data = '';
while($info = mysql_fetch_object($sql)) {
foreach($keys as $fieldName) { // Loop through the array of headers as we fetch the data
$row[] = escape_csv_value($info->$fieldName);
} // End loop
$data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
$row = ''; // Clear the contents of the $row variable to start a new row
}
// Start our output of the CSV
/*header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");*/
echo $col_headers.$data;
} else {
// Nothing needed to be output. Put an error message here or something.
echo 'No data available for this CSV.';
}
OK. First you have to Save the CSV file. If you set headers as you mentioned the file will be automatically downloaded. Please read this article on this.
http://us2.php.net/manual/en/function.fputcsv.php
Once you create your CSV file you can email it using PHP mail function. If you need some library just check this out. It's easy to implement.
http://www.redvodkajelly.com/code/php-email-class/

html table to CSV or Excel

Alright, I'm starting to go a little crazy...
jQuery Table to CSV export
I'm looking at that thread.
It does work, but the output does everything by each LINE not by the HTML table rows. For example, I have an address that is in one HTML cell:
1234 Berryman Lane
Atlanta, GA 12345
Unit # 54A
That will be THREE rows when it outputs to excel, instead of one cell, with returns in it.
Further, there's no way to strip out the HTML that is inside of the HTML cells with that solution, as far as I know...
Finally, Excel gives a warning when opening that file.
What I'm getting at, is that I'd rather just have something that can take the inner most data in the HTML cells (not including HTML inside of a cell), and rip it to CSV. Is there anything that does this well these days?
UPDATE
Well, I just found the best thing yet, this is pretty perfect:
$table = 'myTable';
$file = 'exportFile';
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= "\"" . $row['Field']."\",";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= "\"" . $rowr[$j]."\",";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
I think this is my keeper. It goes to a CSV file with no issues, loads in Excel with no issues, it's my dream come true!
well, you can always use the same markup in excel as it can render html if you use the .xls file type, render the html table and change the content type to "application/vnd.ms-excel" specify a filename for that response as *.xls and you should have a usable excel sheet.
If there are no dobule quotes in the data, you can wrap the content of each cell in double quotes so your data looks like:
"...","...","..."
Now you can have commas in the data. You may also need to deal with new lines and returns in the data, probably best to remove them completely but that's up to you.
Thanks for all suggestions. As stated in my edited post, this script below was a great solution:
$table = 'myTable';
$file = 'exportFile';
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= "\"" . $row['Field']."\",";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= "\"" . $rowr[$j]."\",";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
I think this is my keeper. It goes to a CSV file with no issues, loads in Excel with no issues, it's my dream come true!

Categories