PHPExcel generate html instead of xls - phpexcel

I got stuck in PHPExcel issue. To generate xls file I use the following code
require_once dirname(__FILE__) . '/PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Data');
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
If I launch this php file directly I recieve correct xls file. So this code works correctly.
But I have to add launchinig this code on form submit. And in such case I recieve html file with filename "01simple.xlsx".
Why it happened? Any ideas?
Thanks in advance.

You can add ob_end_clean(); before the output is rendered.

Related

how to set the download path in php

I'm a web developer.
DownloadController.php
$local_file = 'file.zip';
$download_file = 'd:\temp\download.zip';
if(file_exists($local_file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($local_file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($local_file));
readfile($download_file);
}
I hope download the 'file.zip' and downloaded path that 'd:\temp\download.zip'
Anyone help me!
Thank u.
You can use following code to download a file:
return response()->download($pathToFile);
OR
return response()->download($pathToFile, $name, $headers)
The download method may be used to generate a response that forces the user's browser to download the file at the given path. The download method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
Docs

PHPExecel file is empty when send as in attachment

An excel file is created using phpexcel which is saved in the folder with all the data. The same file cannot be send as an attachment in the mail. I would also like to upload the excel in the form in order to make changes.
Please advice. Here is the code.
<?php
//include PHPExcel library
require_once "Classes/PHPExcel.php";
require_once "Classes/PHPExcel/IOFactory.php";
if (!empty($_POST['submit'])) {
//give a filename
$dtime = date('Y-m-d H-i-s');
$dtimeFile = date('Y-m-d-H-i-s');
date_default_timezone_set('Asia/Singapore');
$filename = 'myexcel'.$dtimeFile.'.xls';
$path = __DIR__;
//set headers to download file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$filename);
// create new PHPExcel object
$objTpl = new PHPExcel;
// set default font
$objTpl->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objTpl->getDefaultStyle()->getFont()->setSize(8);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, "Excel5");
// writer already created the first sheet for us, let's get it
$objSheet = $objTpl->getActiveSheet();
// rename the sheet
$objSheet->setTitle('My Personal Details');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:C1')->getFont()->setBold(true)->setSize(12);
$objSheet->getStyle('A2:C2')->getFont()->setSize(12);
// write header
$objSheet->getCell('A1')->setValue('Name');
$objSheet->getCell('B1')->setValue('Email');
$objSheet->getCell('C1')->setValue('Location');
// we could get this data from database, but for simplicty, let's just write it
$objSheet->getCell('A2')->setValue(stripslashes($_POST['name']));
$objSheet->getCell('B2')->setValue(stripslashes($_POST['email']));
$objSheet->getCell('C2')->setValue(stripslashes($_POST['location']));
// // autosize the columns
// $objSheet->getColumnDimension('A')->setAutoSize(true);
// $objSheet->getColumnDimension('B')->setAutoSize(true);
// $objSheet->getColumnDimension('C')->setAutoSize(true);
// $objSheet->getColumnDimension('D')->setAutoSize(true);
$objWriter->save('php://output');
$to = "cloudinnovates#hotmail.com";
$subject = $filename;
$from = "shabs0#hotmail.com";
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"1a2a3a\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
."--1a2a3a\r\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."Attached is the file number \"".$filename."\"\r\n\r\n"
."--1a2a3a\r\n";
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$message .= "Content-Type: application/vnd.ms-excel; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
."\r\n"
.chunk_split(base64_encode($content))
."--1a2a3a--";
// Send email
//
$success = mail($to, $subject, $message, $headers);
if (!$success) {
echo "Mail to ".$to." failed .";
} else {
echo "Success : Mail was send to ".$to;
}
}
//*************** upload file ***************//
if (!empty($_POST['btn-upload'])) {
$file = 'file';
$Reader = PHPExcel_IOFactory::createReaderForFile($file);
$Reader->setReadDataOnly(true);// set this, to not read all excel properties, just data
$objXLS = $Reader->load($file);
$value = $objXLS->getSheet(0)->getCell('A1')->getValue();
$objXLS->disconnectWorksheets();
unset($objXLS);
}
?>
I'm not familiar with PHP Excel and have not worked with PHP for a long time, but something stands out to me in your code.
You initialize a variable for the file name
$filename = 'myexcel'.$dtimeFile.'.xls';
and attempt to read the content of the file like this
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
But you don't appear to actually save your Excel sheet to that file. Rather, you seem to write it to the output stream of the current PHP page.
$objWriter->save('php://output');
Setting the content-disposition header
header('Content-Disposition: attachment;filename='.$filename);
tells the browser opening this PHP page what to do with the data returned by the PHP page, but does not save the file to your local server, so that it can be attached to an email on that server.
You will need to save the Excel file to a location on your local server before it is attached to the email.

Phpexcel crypted output data

My PHPExcel Export works and it is proper if i save the file, but when i want also make an output to the browser than i get the same file totaly crypted.
See hardcopy:
I work on PHPExcel 1.80
Here my code:
/** PHPExcel */
require_once 'inc/phpExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
.....
// Save Excel 2003 file
// redirect output to client browser
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachement;filename="synt_ch_fct_export.xls"');
//header('Cache-Control: max-age=0');
$objWriter->save('php://output');
$objWriter->save('img/test.xls');
I have searched the web, but i couldn't find any solution.
If you have an idea ???
THX in advance

Show pdf in symfony2

I want to show a pdf, but I did this and I only gets to download the pdf: This is my code:
$response = new BinaryFileResponse($path);
$response->trustXSendfileTypeHeader();
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file . '.pdf');
return $response;
Any idea?
Have you tried setting Content-Type header?
$response->headers->set('Content-Type', 'application/pdf');
Also, ditch that setContentDisposition call since DISPOSITION_ATTACHMENT value forces your browser to download the file.

WordPress fopen getting directory link

I'm using fwrite to create an html file in a folder within my plugin. The following code now allows me to write to the folder, but the link it tries to open is the full system path.
function buildFrameFile($html, $filename){
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$filename= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
$fh = fopen($filename, 'a');//open file and create if does not exist
fwrite($fh, $html);//write data
fclose($fh);//close file
return $filename;
}
The path it now opens is:
/var/chroot/home/content/##/########/html/wp-content/plugins/my-plugin/html/79dda339bad8e65c425e580d62f41fa1.html
I need it to open from here:
/wp-content/plugins/my-plugin/html/79dda339bad8e65c425e580d62f41fa1.html
I'm not sure how to go about this.
I solved my problem. I ended up changing the code from:
function buildFrameFile($html, $filename){
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$filename= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
$fh = fopen($filename, 'a');//open file and create if does not exist
fwrite($fh, $html);//write data
fclose($fh);//close file
return $filename;
}
To:
function buildFrameFile($html, $filename){
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$filename2= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
$fh = fopen($filename2, 'a');//open file and create if does not exist
fwrite($fh, $html);//write data
fclose($fh);//close file
return $filename;
}
This way the file gets saved to the folder and only returns the actual name of the file not the whole link to the file.
Then in my header I changed the code from:
header("Location: /confirm" . $nvp_str . "&filename=" . $filename);
To:
header("Location: /confirm?" . $nvp_str . "&filename=" . '/wp-content/plugins/my-plugin/html/' . $filename . ".html");
and the iframe in my page calls the value of &filename which then returns the proper link to my file created and it loads perfectly!
First of all, you can rely on Wordpress' defines (or functions) to determinate the paths without any dirty hacks:
http://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Available_Functions
http://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants
Then again you can check things using PHP functions like file_exists(), is_dir(), is_writable():
http://pl1.php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.file-exists.php
http://pl1.php.net/manual/en/function.is-writable.php
To avoid complex fopen, fwrite, fclose handlers, you can go for file_put_contents() function there too. Either in appending or overwriting mode:
http://pl1.php.net/manual/en/function.file-put-contents.php
Not sure how relevant, but keep in mind if this is written by the webserver, you need to make sure the directory has write permissions there. Easiest way would be chmod 777 directory from shell, or SITE CHMOD 777 directory from FTP.
Your issue is most likely connected to weird godaddy's setup.
You can find more information here: http://www.quest4.org/etc/godaddy_path.htm
There's also a similiar issue posted here:
WordPress's plugins_url() function not working on shared hosting

Resources