$filename = "PM.xls";
$exists = file_exists('PM.xls');
if($exists)
{
unlink($filename);
}
$filename = "PM.xls";
$fp = fopen($filename, "wb");
$sql = "SELECT DATE_FORMAT(jobcard.Open_date_time,' %d-%b-%y') AS datee,vehicles_data.Frame_no, jobcard.Jobc_id,jobcard.serv_nature,jobcard.Customer_name,jobc_invoice.Lnet, jobc_invoice.Pnet, jobc_invoice.Snet, jobcard.Mileage,customer_data.cust_type,vehicles_data.model_year,jobcard.Veh_reg_no,jobcard.comp_appointed, customer_data.mobile,IF(variant_codes.Make IS NULL,'Others',variant_codes.Make) as make FROM `jobcard` LEFT OUTER JOIN jobc_invoice ON jobcard.Jobc_id=jobc_invoice.Jobc_id LEFT OUTER JOIN vehicles_data ON jobcard.Vehicle_id=vehicles_data.Vehicle_id LEFT OUTER JOIN variant_codes ON vehicles_data.Model=variant_codes.Model LEFT OUTER JOIN customer_data ON jobcard.Customer_id=customer_data.Customer_id ORDER BY `make` ASC";
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
$schema_insert = "";
$schema_insert_rows = "";
while($row = mysqli_fetch_row($result))
{
$insert = $row[0]. "\t" .$row[1]. "\t".$row[2]. "\t".$row[3]. "\t".$row[4]. "\t".$row[5]. "\t".$row[6]. "\t".$row[7]. "\t".$row[8]. "\t".$row[9]. "\t".$row[10]. "\t".$row[11]. "\t".$row[12]. "\t".$row[13]. "\t".$row[14]. "\t".$row[15];
$insert .= "\n"; // serialize($assoc)
fwrite($fp, $insert);
}
Above code successfully creates the file on server but can't replace it, Instead of creating the file on server i want it download the file on user end. Should I use any excel library as I have to name excel sheet as well.
First, you creating TSV file with XLS extension. If you need to create XLS document, you should use PHPExcel or so.
If CSV is enough for you, there are fputcsv available since 5.1 and you can stream file data directly to the user agent.
$filename = "PM.csv";
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.addcslashes($filename, '\\"').'"');
$fp = fopen('php://output', 'wb');
// ...
while($row = mysqli_fetch_row($result))
{
fputcsv($fp, $row, ',', '"');
}
fclose($fp);
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.
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 trying to create a PHP page that opens the query and automatically updates the csv file with a new value.
I disc location I have file "graph.csv" with date, and COUNT from SQL Query.
I try open this file and add new row everytime when page is loaded. But, currently browser try save and overwrite file manual. php and csv file are in the same location.
<?php
$connect = oci_connect("login","pass","db");
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=graph.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('TIME','Orders'));
$query = "SELECT column1, column2 FROM table1";
$result = oci_parse($connect, $query);
$r=oci_execute($result);
while ($row = oci_fetch_array($result, OCI_BOTH))
{
$handle = fopen("graph.csv", "a");
$handle = fputcsv($output, $row);
}
$handle = fclose($output);
?>
When I export data to csv file and open file with wordpad myfield Sr. No. looks like Sr. No. I don't want double space after Sr. and also don't wanr space after No. Code is as follow.
$filename = "file.csv";
$fp = fopen('php://output', 'w');
$array = array('Sr. No.','Name','DOB','Address');
$header = str_replace('',' ', $array);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header,',',' ');
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
$row = array_merge(array($i), $row);
fputcsv($fp, $row);
$i++;
}
If yo don't want your headers line to conform to the rules for a CSV, then just write that one line using fwrite() rather than fputcsv()
$headerLine = 'Sr. No,Name,DOB,Address';
fwrite($fp, $headerLine);
So I have this code to generate a CSV file from mysql database. But however, it downloads the code instead of saving it to the directory for further use (need to send that file via phpmailer).
What changes should I do to make it save the file to the directory.
$array = array();
if(file_exists('records_monthly.csv'))
{
unlink('records_monthly.csv');
}
# Headers
$array[] = array("Serial Number","Donation Type", "Amount", "Status", "Date", "Orderref", "DIN");
$serial=1;
try
{
$s = $conn->query("SELECT c.firstname AS firstname, c.lastname as lastname, c.address AS address, c.city AS city, c.postalnumber AS postalnumber, c.email AS cemail, d.donation_type as donation_type, d.donation_amount as donation_amount, d.orderref as orderref, d.status as status, d.donation_on AS donation_on, d.din as din from customers c, donations d where c.email = d.donator");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($donations = $s->fetch(PDO::FETCH_OBJ))
{
if($donations->status == 0)
{
$array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Failed",$donations->donation_on,$donations->orderref,$donations->din);
}
else
{
$array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Success",$donations->donation_on,$donations->orderref,$donations->din);
}
}
array_to_csv_download($array,"records_monthly.csv",",");
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
Write directly to the named file rather than to php://memory and don't send headers and output to the browser
function array_to_csv_without_download($array, $filename = "export.csv", $delimiter=";") {
$f = fopen($filename, 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
fclose($f);
}