I am not really a PHP expert as my past experience is mostly geared towards the system engineering side.
I am facing a problem with PHPExcel which gives me this error "Cannot modify header information - headers already sent by in line 1" when I want to output my XLSX file to the browser.
Here is the sample of my code
$host="localhost";
$uname="lol";
$pass="lol123";
$database = "lol12345";
$table="MemReport";
$table1="CPUReport";
$table2="TrafficReport";
$table3="HDDReport";
// create a file pointer connected to the output stream
$output = fopen('Memory.csv', 'w+');
$output1 = fopen('CPU.csv', 'w+');
$output2 = fopen('Traffic.csv', 'w+');
$output3 = fopen('HDD.csv', 'w+');
// output the column headings
fputcsv($output, array('HostName','Date','Time','Percent','TholdDescription'));
fputcsv($output1, array('HostName','Date','Time','Percent','TholdDescription'));
fputcsv($output2, array('HostName','Date','Time','Percent','TholdDescription'));
fputcsv($output3, array('HostName','Date','Time','Percent','TholdDescription'));
// fetch the data
mysql_connect($host, $uname, $pass);
mysql_select_db($database);
echo mysql_error();
$rows = mysql_query("SELECT * FROM $table order by date ASC, Time ASC");
echo mysql_error();
$rows1 = mysql_query("SELECT * FROM $table1 order by date ASC, Time ASC");
echo mysql_error();
$rows2 = mysql_query("SELECT * FROM $table2 order by date ASC, Time ASC");
echo mysql_error();
$rows3 = mysql_query("SELECT * FROM $table3 order by date ASC, Time ASC");
echo mysql_error();
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
while ($row1 = mysql_fetch_assoc($rows1))
fputcsv($output1, $row1);
while ($row2 = mysql_fetch_assoc($rows2))
fputcsv($output2, $row2);
while ($row3 = mysql_fetch_assoc($rows3))
fputcsv($output3, $row3);
include '/tmp/Classes/PHPExcel/IOFactory.php';
$inputFileType = 'CSV';
$inputFileNames = array('HDD.csv','Traffic.csv','CPU.csv','Memory.csv');
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$inputFileName = array_shift($inputFileNames);
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
foreach($inputFileNames as $sheet => $inputFileName) {
$objReader->setSheetIndex($sheet+1);
$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
//var_dump($sheetData);
//var_dump($sheetData);
$myfile = "Report.xlsx";
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=$myfile");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
any help is appreciated, most of my code has been copy and pasted and then edited to my knowledge, also i was able to get to email the xlsx file but just have problem sending it for download.
I don't mind reading the file from the directory for download.
regards,
Lin
No spaces or tabs, no error messages, no newline characters, no BOM markers, no other output whatsoever.
Note that the error message you're seeing tells you which file/line was responsible for the output headers already sent by xxx in line 1.... so that's where to look.
At line 1 of a file, it's most likely to be something before your opening <?php tag, or a file saved with a BOM header
Related
I am trying to write a simple PHP code to export to excel the data selected between two dates. On clicking the 'Export to Excel' button in the HTML page which will redirect to php file with the below code, my excel is not getting downloaded. Can someone tell me where the error is and what modification needs to be made. Tell me in the simplest way possible.
<?php
include ("conn.php");
if(isset($_POST["export"]))
{
$connect = mysqli_connect("localhost", "root", "", "cruddatabase");
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('ID Company Name','Company Type','Name','Email','Contact Number','Anniversary Date','Organisation Name','Meeting','Timeline For Conversation','Currency','Card','Locations'));
$query = "SELECT * FROM crudtable WHERE adate >= '$fdate' AND adate <= '$tdate' ORDER BY adate DESC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
}
?>
I'm having a problem writing the results of a MySQL query to a file using php. There are definitely results from the search, and the file is created, but when you open the file it's empty. I think it's something to do with how I'm writing to the file, but I'm not sure.
$result = mysql_query($compsel);
if(!result) die("unable to process query: " . mysql_error());
$fp = fopen('results.csv','w');
mysql_data_seek($result,0); //set data pointer to 0
$rw = mysql_fetch_array($result, MYSQL_ASSOC);
print_r($rw);
foreach ($rw as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
Thanks in advance!
Here's an example:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
You can modify it to suit your needs.
Source: http://code.stephenmorley.org/php/creating-downloadable-csv-files/
I am using below code to export CSV file using fputcsv in PHP. Code works proper and CSV file generates. All the values/records are coming from database. But I want to add dollar ($) symbol with some of column values.
Code for exporting CSV file.
$filename1 = "All Months.csv";
ob_end_clean();
$fp1 = fopen('php://output', 'w');
ob_start();
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename='.$filename1);
fputcsv($fp1, array('Month', 'Year', 'Total Production', 'Credit Adjustments', 'Net Production', 'Hygiene Production', 'Collections', 'Account Receivable Total', 'New Patients', 'Break Even Points', 'Net Income', 'Hygiene %'));
$query = $db->query("SELECT Month, Year, Total_Production, Credit_Adjustments, Net_Production, Hygiene_Production, Collections, AC_Receivable_Total, New_Patients, Break_Even_Points, Net_Income, Hygiene FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}
exit();
Snapshot of exporting file -
If you want just to add $ sign you can do it this way:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$row['the_field_you_want'] = '$'.$row['the_field_you_want']
fputcsv($fp1, $row);
}
While using select query itself you can concat $ symbol. Like below
$query = $db->query("SELECT concat('$',Net_Income) as Net_Income FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}
When i open the Excel file message appear:
the file you are trying to open, 'filename".xls', is in a different format than specified by the file extension. verify that the fileis not corrupted and is from a trusted source before opening the file."
The output is like this:
ÐÏࡱá;þÿ þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
>¶#d‹‹dggÿÿÿÿÿ .....
Here is my code..
<?php
require_once 'database.php';
include 'PHPExcel.php';
$phpExcel = new PHPExcel();
$phpExcel->getActiveSheet()->setTitle("My Sheet");
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Name.')
->setCellValue('B1', 'Age');
$qry_table = ("SELECT * FROM MEMBERS");
$inc=2;
while($data_array = mysql_fetch_array($qry_table))
{
$name = $data_array['Name'];
$age = $data_array['Age'];
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
$inc++;
}
$phpExcel->setActiveSheetIndex(0);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
exit;
Where's your "mysql_query()" to query the database?
Change
$qry_table = ("SELECT * FROM MEMBERS");
to
$qry_table = mysql_query("SELECT * FROM MEMBERS");
//Edit:
And you've got a pointer ref. to an a variable which does not exsits
Change:
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
to:
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name);
$phpExcel->setActiveSheetIndex(0)
->setCellValue('B'.$inc, $age);
When you get this error, we always recommend opening the file in a text editor and checking for leading or trailing white spaces (spaces, tabs, newlines), or a BOM marker, or any obvious PHP error messages in plain text in the file.
Try saving the file to your webserver, then opening it and see if the same error occurs
Greetings,
I am having trouble figuring out how to properly use PHP in general and PHPExcel in particular. I have read multiple posts on this topic and yet I've been running around in circles. Here is the relevant portion of my jacked up code:
$viewinv = mysql_connect($sqlsrv,$username,$password);
if (!$viewinv) { die('Could not connect to SQL server. Contact administrator.'); }
mysql_select_db($database, $viewinv) or die('Could not connect to database. Contact administrator.');
$query = "select unit_id,config,location from inventory;";
$result = mysql_query($query);
if ($result = mysql_query($query) or die(mysql_error())) {
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('blah');
$rowNumber = 1;
$headings = array('Unit ID','Config','Location');
$objPHPExcel->getActiveSheet()->fromArray(array($headings),NULL,'A'.$rowNumber);
$rowNumber++;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myFile.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
PHPExcel is definitely outputting data from the query, I can see bits and pieces of plaintext, but it is surrounded by a ton of random characters as if though I am looking at the contents of a compressed or compiled piece of data.
For example:
PKâh¿>G’D²Xð[Content_Types].xml”MNÃ0…÷œ"ò%nY „švAa •(0ö¤±êØ–gúw{&i‰#ÕnbEö{ßøyìÑdÛ¸l mð¥‘×ÁX¿(ÅÛü)¿’òF¹à¡;#1_滘±Øc)j¢x/%ê…Eˆày¦
Any pointers would be extremely appreciated
Your problem is certainly in outputting more content than just Excel data (which is contained in output buffer).
To solve your problem, just call
ob_clean(); //this will clean the output buffer
before sending header.
The problem will likely be resolved by matching the correct writer types to the correct content-types and file extension.
XLSX (office 2007+):
Writer : Excel2007 (PHPExcel_Writer_Excel2007)
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
XLS (before office 2007):
Writer : Excel5 (PHPExcel_Writer_Excel5)
Content-Type: application/vnd.ms-excel