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
Related
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).
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
For better or worse, I am storing binary information in a database table and am having a problem retrieving it. Each BLOB has a newline prepended to it upon retrieval, at least, I believe it's upon retrieval, as the binary object in the table is exactly the same size as the source file.
I've searched for a similar problem to mine, and the closest I have found is this However, I am using PDO instead of mysql_* and I have checked for empty lines prior to the opening
Here's the retrieval function stored in a separate file that I'm including in my test:
(in raw.php):
function return_raw_rawid($raw_id) {
$data = array();
$aggregate_data = array();
$sql = "SELECT * FROM `raw` WHERE `raw_id` = :rawid";
try {
$db_obj = dbCore::getInstance();
$query = $db_obj->dbh->prepare($sql);
$query->bindValue(':rawid', $raw_id);
if ($query->execute()) {
while($results = $query->fetch(PDO::FETCH_ASSOC)) {
$data['raw_id'] = $results['raw_id'];
$data['filename'] = $results['filename'];
$data['mime_type'] = $results['mime_type'];
$data['file_size'] = $results['file_size'];
$data['file_data'] = $results['file_data'];
$data['test_id'] = $results['test_id'];
$data['user_id'] = $results['user_id'];
$data['time'] = date('Y-m-d H:i:s', $results['time']);
$aggregate_data[] = $data;
} // while
} // if
$query->closeCursor();
return $aggregate_data;
} catch (PDOException $ex) {
$errors[] = $ex;
} // catch
}
Here's the code I'm testing it with in a separate file:
<?php
include 'core/init.php'; // Contains protect_page() and includes for return_raw_rawid
protect_page();
$blob_id = 20;
$blob = return_raw_rawid($blob_id);
$data = ltrim($blob[0]['file_data']);
$name = ltrim($blob[0]['filename']);
$size = ltrim($blob[0]['file_size']);
$type = ltrim($blob[0]['mime_type']);
header("Content-type: $type");
header("Content-length: $size");
header("Content-disposition: attachment; filename=$name");
header("Content-Description: PHP Generated Data");
echo $data;
When I load this page in my browser, it will prompt me to download the file identified by blob_id and has the correct filename and type. However, upon downloading it and opening in ghex, I see that the first byte is '0A' Using cmp original_file downloaded_file I determine that the only difference is this first byte. Googling led me to the ltrim() function that I've (perhaps too) liberally applied above.
I can't tell for sure if this problem is not being caused during upload, though as I said before, I don't believe it is since the "file_size" value in phpmyadmin is exactly the same as the source file. I'm not sure if the use of the aggregate_data array in the retrieval function could be to blame or what.
Any help is greatly appreciated!
Are you sure those 4 header lines are being properly executed? 0x0A is the newline char. You could have a newline in your core/init.php triggering output, and the headers are never executed. With display_errors/error_reporting off, you'd never see the warnings about "headers not sent - output started at line X...".
I have problem with writing csv file using fputcsv. Its putting the page html also into the csv file. Whats wrong with my code ?
//Excel header
header("Content-Disposition: attachment; filename=\"Delivery_Reports.csv\";" );
header("Content-type: application/vnd.ms-excel");
$out = fopen("php://output", 'w');
$flag = false;
// $result = mysql_query("SELECT * FROM senderids ") or die('Query failed!');
//$sel="SELECT number as MobileNumber ,snum as Sender , msg as Subject ,crdate as Date ,status FROM savemsg WHERE userID='".$_SESSION['id']."' ".$str." ORDER BY sn DESC ";
$result = mysql_query("SELECT `count`, `dnd`, `credit`, `sender_id`, `to`, `message`, `status` FROM `reports` WHERE `unq_id` = '$dlr_id'");
while(false !== ($row = mysql_fetch_assoc($result))){
if(!$flag){
$list = array(
"Total"=>"Total",
"DND"=>"DND",
"Credits"=>"Credits",
"From"=>"From",
"To"=>"To",
"Message"=>"Message",
"Status"=>"Status"
);
// display field/column names as first row
fputcsv($out, array_keys($list), ',', '"');
$flag = true;
}
// array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
You can't guarantee, from within a snippet of code, that nothing else will be output. If the code before this snippet is using output buffering, you can discard the HTML using ob_end_clean. If the code after this snippet is causing the problem, you can simply call die to keep it from running at all. However, if the code before this snippet is outputting HTML directly to the browser, or the code after it outputs HTML and absolutely has to run, then you'll have to modify that code in order to solve your problem.
As Tim mentioned, print, echo and outputting to the pseudo-file php://output do exactly the same thing.
You can also use the keyword continue just before you close the file (fclose($f);). This also works lovely.
You can also use exit; after fclose($out); which stopped the output from scraping my html.
I know it's an old question but it gets found in Google so adding this.
If the HTML is being output by the CMS such as WordPress etc. before you try to create the file, it might help to add ob_clean(); and ob_start(); before you output the header.
For example:
function create_csv($records, $columns){
ob_clean();
ob_start();
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="Export.csv"');
$fp = fopen('php://output', 'w+');
// Generate the file content.
fclose($fp);
die();
}
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