I have written the following script which is to create a CSV file based on content from a Database. The script itself works perfectly and creates the CSV file and populates it as expected. The problem is that when the file downloads automatically it is empty, but when downloading it from the hosting server over FTP it is filled with the information.
Is the file just downloading too soon before the file is successfully written? Is there anything that can be done to fix this issue?
<?php
// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");
$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');
$handle = fopen($filename, 'w');
fputcsv($handle, $headers, ',', '"');
$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);
while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);
$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);
fputcsv($handle, $row, ',', '"');
}
// rewind the "file" with the csv lines
fseek($handle, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// make php send the generated csv lines to the browser
fpassthru($handle);
fclose($handle);
?>
After further testing and finding a similar post on the topic, I have found a fix. Rather than using fopen() on a file, I wrote the data to memory and it is now working correctly.
<?php
// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");
$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');
//$handle = fopen($filename, 'w');
$handle = fopen('php://memory', 'w');
fputcsv($handle, $headers, ',', '"');
$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);
while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);
$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);
fputcsv($handle, $row, ',', '"');
}
// rewind the "file" with the csv lines
fseek($handle, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// make php send the generated csv lines to the browser
fpassthru($handle);
fclose($handle);
?>
try putting this
// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");
ob_start(); //start output buffering
$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');
$handle = fopen($filename, 'w');
fputcsv($handle, $headers, ',', '"');
$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);
while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);
$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);
fputcsv($handle, $row, ',', '"');
}
ob_end_clean(); //ending output buffering.
// rewind the "file" with the csv lines
fseek($handle, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// make php send the generated csv lines to the browser
fpassthru($handle);
fclose($handle);
Related
I have to fetch the result of a mysql query to a "user friendly" excel (.xls or .xlsx) table.
I don't want to use imports or packages for php.
This is what I got so far:
<?php
function query_to_csv($database, $query, $filename, $attachment = false, $headers = true) {
if ($attachment) {
// send response headers to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysqli_query($database, $query) or die(mysqli_error($database));
foreach ($result as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
This is the
Result
How can I get the array sperated in different Cells?
Sadly I had to use a library named PHP Excel (old) or PhpSpreadsheet (new).
$objReader->setDelimiter(',');
That's the PHP Excel Function to set the Delimiter.
I have a piece of codes which is exporting csv and few image files inside a zip file, The csv and images were zipped and exported in a zip file successfully. However, my SQL data did not populate the csv file. Only a empty blank sheet in the csv file. what am i doing wrong?
if($_GET['exportdata'] == 'true'){
$datefrom = $_GET['datefrom'];
$dateto = $_GET['dateto'];
$filename = "data.csv"; // Create file name
$f = fopen('php://memory', 'w');
$fields = array('Sample No.',
'Wet Density Mg/m3');
fputcsv($f, $fields);
$query = "SELECT [SampleNo], [Density]
FROM EXPORT_DREDGER WHERE [Date] between ? and ?";
$params = array($datefrom, $dateto);
$stmt = sqlsrv_query($conn2, $query, $params);
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)){
$row[0];
$row[1];
fputcsv($f, $row);
}
//move back to beginning of file
fseek($f, 0);
//export image and csv files as zip file
$files = array('trip_image/A2002175102616/A2002175102616_img_0001.jpg', 'trip_image/A2002175102617/A2002175102617_img_0001.jpg', $filename);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file, basename($file));
}
$zip->close();
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
fpassthru($f);
}
Im having a problem of exporting my csv. Yes it can export but when it exported the colmun name is included. How can i remove the first row (column name) after i exported?
Tried looking for other solution yet it doesnt fit on my program
<?php
//include database configuration file
include 'config2.php';
//get records from database
$query = $db->query("SELECT * FROM maternalproblem ");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "maternalproblem" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format =line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['MPID'], $row['district_id'], $row['barangay_id'], $row['PID'], $row['tuberculosis'],$row['sakit'],$row['diyabetes'],$row['hika'],$row['bisyo']);
df.to_csv($filename , header=False);
fputcsv($f, $lineData, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;
?>
I just need to export the data and not with the column name. Thank you
It would probably be simpler to just not put the column titles out into the file
So remove these lines
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);
I'm working with Moodle api functions and I want to get all grades for enrolled users in a specific course. The purpose is to print all grades in an excel file. I tried to get the data from gradereport_user_get_grade_items but its not working here is my php code.
<?php
require_once('./curl.php');
$course_id=4;
$domainname = '........'; //paste your domain here
$wstoken = 'e521817f5cf9798926e0563d452b7975';//here paste your getgradetoken
$wsfunctionname = 'gradereport_user_get_grade_items';
$restformat='xml';//REST returned values format
$grade = array( 'courseid' => $course_id , 'user_id'=> $user_id );
$user_grades = array($grade);
$params = array('user_grades' => $user_grades);
//REST CALL
header('Content-Type: text/plain');
$serverurl = $domainname . "/webservice/rest/server.php?wstoken=" . $wstoken . "&wsfunction=" . $wsfunctionname;
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backwardcompatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
//EXCEL
header("Content-Disposition: attachment; filename=\"gradereport.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
foreach ($params as $data)
{
if (is_array($data)){
foreach ($data as $v) {
fputcsv($out, $v,"\t");
}
}
}
fclose($out);
?>
So my following code generated a CSV based on specified tables and generates file and saves to downloads/filename.csv however its not asking the user to download once its generated. Any ideas why?
Here is the code:
PHP
header("Content-type: text/csv");
// Connect to the database
$mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
// output any connection error
if ($mysqli->connect_error) {
die('Error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error);
}
$tables = array('invoices', 'customers', 'invoice_items'); // array of tables need to export
$file_name = 'invoice-export-'.date('d-m-Y').'.csv'; // file name
$file_path = 'downloads/'.$file_name; // file path
$file = fopen($file_path, "w"); // open a file in write mode
chmod($file_path, 0777); // set the file permission
// loop for tables
foreach($tables as $table) {
$table_column = array();
$query_table_columns = "SHOW COLUMNS FROM $table";
// fetch table field names
if ($result_column = mysqli_query($mysqli, $query_table_columns)) {
while ($column = $result_column->fetch_row()) {
$table_column[] = $column[0];
}
}
// Format array as CSV and write to file pointer
fputcsv($file, $table_column, ",", '"');
$query_table_columns_data = "SELECT * FROM $table";
if ($result_column_data = mysqli_query($mysqli, $query_table_columns_data)) {
// fetch table fields data
while ($column_data = $result_column_data->fetch_row()) {
$table_column_data = array();
foreach($column_data as $data) {
$table_column_data[] = $data;
}
// Format array as CSV and write to file pointer
fputcsv($file, $table_column_data, ",", '"');
}
}
}
// close file pointer
fclose($file);
// ask either save or open
header("Pragma: public");
header("Expires: 0");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename='{$file_name}';" );
header("Content-Transfer-Encoding: binary");
// open a saved file to read data
$fhandle = fopen($file_path, 'r');
fpassthru($fhandle);
fclose($fhandle);
$mysqli->close();
die;
This should allow you to select the field you want to write to the CSV file, and their order.
// loop over the rows, outputting them
while($row = $results->fetch_assoc()) {
$data = [
$row["myfirstfield]",
$row["mysecondfield"],
....
];
fputcsv($output, $data);
}