I'm new with PHPEXCEL. My problem is PHPEXCEL(the code below) includes HTML in CSV output.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
The quick brown fox jumps over the lazy dog.
<?php
/** Include PHPExcel */
require_once dirname(__FILE__) . '/PHPExcel_1.8.0_doc/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'ID')
->setCellValue('B1', 'Name')
->setCellValue('C1', 'Description')
->setCellValue('D1', 'Type');
//ID
for($i=2; $i<=6; $i++){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$i, $i-1);
}
//Name
for($i=2; $i<=6; $i++){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$i, "Game" . ($i-1));
}
// Miscellaneous glyphs, UTF-8
/*$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
*/
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('List of Games');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="gcg_list.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
</body>
</html>
Output:
The quick brown fox jumps over the lazy dog. Џࡱက; ş+'ٰ#Hh 䄀Untitled SpreadsheetUnknown CreatorUnknown Creator#7Uҁ#7Uҁ ̇рB=%r8X"1܀Calibri�� �� �� �� �� �� �� �� �� �� �� �� �� �� �� ‸3f̀̿fff̙̙̀̌̿̿̿̀̿̀3f3̌̀̀fff3f3f33333f33333" List of GamesAAg恀 IDNameDescriptionTypeGame1Game2Game3Game4Game5 ̇р*+Dffffff濧ffffff濨迩迡"dXX333333ӿ333333ӿU}$ }$ }$ }$ # # # # >#ddgg Ս՜.+,0HPX`hp x䄀 WorksheetFeuilles de calculRoot Entry F7Uҁ7UҁSummaryInformation( F耀Workbook FDžDocumentSummaryInformation8 F쀀
If I make my code pure PHP(without HTML tags), PHPEXCEL will output correct CSV file.
Output:
ID Name Description Type
1 Game1
2 Game2
3 Game3
4 Game4
5 Game5
Can you help me know what's wrong with the code? Thanks
When you have HTML in your code, your webserver sends the HTML to your user. At this point, the webserver tells the browser accessing it what the format of the content it is sending is. (in your case, HTML, because that's at the top of your page)
You then output the PHPExcel file afterwards, but it's too late by this stage, because the user's browser has already been told that it's receiving content of the MIME type "text/html". There is no mechanism in place to tell a browser, in the middle of a request, that the content type has changed, and to start processing it differently.
I've created a sepate php file, called it and it works like charm. I want to make Mark Baker the answer however its a comment :)
Related
I am converting HTML to excel file.
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=test.xls");
?>
<tr><td>(8.47%)</td></tr>
Here i want to display (8.47%) in display in excel but when i open the excel file it automatically convert and display as -8.47 .
I want my value to be display as (8.47%) not as -8.47.
Does quoting works ? Like you do in excel.
<tr><td>('8.47%)</td></tr>
Edit:
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=test.xls");
?>
<table>
<tr><td>(8.47%)</td></tr>
</table>
I just add <table></table> around and works for me
I have problem. I created a web page with upload files, I have database (MySQL) with correctly URL to file (file path) (in database is only url to the file, file is in folder on the server). And now I trying write/search php script to download this file what was uploaded. All at web works well, but this download scripts don't work. I read and I think best way for me will be download with 'header', but I was trying and nothing. File is download to our disk, name is correctly, file extension ok, file is open in correct program, but if file have in name chars (';',':' etc.) file is download without these chars and is incorrectly (lack of extension, bad name). And second problem: all downloaded files are empty (0 b size), all is ok but they are empty, some tips ? Thanks in advance for help
My bad download codes:
<?php
$data=date('Y-m-d_H:i:s');
$nazwa=$_POST['downtitle'];
$urlek=$_POST['downurl'];
$extrozsz=$_POST['downext'];
$filePath = $urlek;
$fileName = $nazwa.$data.".".$extrozsz;
//------------------------------------------------------------------------
// $fd = fopen($filePath,"r");
// $size = filesize($filePath);
// $contents = fread($fd, filesize($filePath));
// fclose($fd);
// header("Content-Type: application/octet-stream");
// header("Content-Length: $size;");
// header("Content-Disposition: attachment; filename=$fileName");
// echo $contents;
//----------------------------------------------------------------------
// set_time_limit(0);
// while( $urlek = $response->fetch() )
// {
// $my_pliki = file_get_contents("$urlek");
// $my_file = fopen("$urlek","w+");
// fwrite($my_file,$my_pliki);
// fclose($my_file);
// }
//----------------------------------------------------------------------------
$quoted = $filePath;
$size = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
?>
The filename parameter has some limits which are well described in RFC6266
So when you want use characters that are not present in the ISO-8859-1 character set then you need to use either filename* header or you need to strip/replace these characters from the filename. Nice solution to do so can be found here
Ok all is now ok, but another problem. I have code for showing news at website. All news are showing at same time (too long site). I wish to have at bottom of website numbers (at all websites under are this for forwarding on second subpage with older news). But how do it? Sup or sub is for small word, numbers etc, but all is retrieved form database:
$zapytanie='SELECT * FROM filetable WHERE Section="Other" ORDER BY ID DESC LIMIT 10';
This is in my php code query for showing latest 10 news, but if I add normally small numbers at bottom how construct code for showing next 10 news (no at where id="10-11" because if I will be have 1 thousand news or more it is too primitive) I must have automated code for showing pages with nextly 10 or 20 news how ?
Thanks, I edit my php at this:
<?php
$data=date('Y-m-d_H:i:s');
$nazwa=$_POST['downtitle'];
$urlek=$_POST['downurl'];
$extrozsz=$_POST['downext'];
$filePath = $urlek;
$fileName = $nazwa.$data.".".$extrozsz;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"" . $fileName."\"");
header("Content-Description: File Transfer");
readfile($filePath);
?>
And all is now ok, but I have one question now: In MySQL database I have title, description, added date, premiere date and I wish to have search field. I done it in input type="search", but what script now use for searching in this specified tables in database, firstly open database this I know, but what later what command is for search in database ? I know about 'like' but some better? And after all return correct result and show all from database where this search word is ok Some tips? Sorry for weak english and thanks.
I have a html file that want pars tags(Title,A,Name,...) and save them to a excel file .
html tags is persian and when save them into excel file not save corectly.
html file:
<html dir="rtl"><head><meta http-equiv="Content-Language" content="fa">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>ÈÇäß ÕæÊ.ÂãæÒÔ.ÇÏÈíÇÊ.ÚæÇãá Ýí ÇáäÍæ.ÇÓÊÇÏ ãÏÑÓ ÇÝÛÇäí.ÌáÓå 1</title>
<meta name="generator" M.H.SAFARZADE TEHRANI E_BANK_JAME_EMAMALI>
for example i want save title but not save corectly . title tag trust value is :
تدريس استاد مدرس افغاني
but save : ÈÇäß ÕæÊ.ÂãæÒÔ.ÇÏÈíÇÊ.ÚæÇãá Ýí ÇáäÍæ.ÇÓÊÇÏ ãÏÑÓ ÇÝÛÇäí.ÌáÓå 1
in php file i do this :
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
header('Content-Type: text/html; charset=utf-8');
and :
$str = mb_convert_encoding($title, "UTF-8");
i can't find answer for my question in web.
please help me ...
thank you
I am working on content based WAP application in which I will have to put
download button on selected content. Content can be (MP3,WAV,MP4,3gp,image). Content name is 9-digit random numeric character like 132432498.mp3, 814274691.mp4.
I tried below code
<?php if(isset($_GET['fileId'])){
$fileid = $_GET['fileId'];
{
i retrieve content content path and name together
like $filename="myserverip/1/3/4/132432498.mp3"
}
then
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$filename.";");
header("Content-Length: ".filesize($filename));
readfile($filename);
exit;
?>
< a href= < ? php echo $filename; ?>>Download < /a> '
But file automatically gets downloading with name 132432498.mp3.
I need help to write name of above content as I desire. How to do this in php?
It could be the case you are providing a name with has spaces, you have to prevent that enclosing it with double quotes, like this:
header('Content-Disposition: attachment; filename="'.$filename.'"');
I got a class that generates a png showing the result on a single page
header('Content-Type: image/png');
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
imagepng($png,'test.png');
imagedestroy($png);
Instead of above, that prints the png successfully, I need to use the script so it generates several dynamically created pngs and be able to parse them in an html page.
Therefore I tried to uncomment the headers and return $png:
return $png;
and on the other side parse it
$png = $obj->pngGeneratorFuntion(1,30,'blank');
imagepng($png);
imagedestroy($png);
The results looks like this
�PNG IHDR.i ��PLTE���U��~tRNS#��fIDAT�c�$=�*y ���K�S����)IEND�B`��PNG IHDR.i ��PLTE���U��~tRNS#��fIDAT�c�$i]���a�P�{O��;>IEND�B`��PNG IHDR.i ��PLTE���U��~tRNS#��fIDAT�c�$Y����a�P�OMY�)"IEND�B`��PNG IHDR.i ��PLTE���U��~tRNS#��fIDAT�c�$yZ/y ���TKX{U#8MIEND�B`��PNG IHDR.i ��PLTE���U��~tRNS#��fIDAT�c�$<�2y ���>�Sq��M�IEND�B`�
and print_r($png) gives
Resource id #7
How can I achieve this. Thanks!
You can try base64_encode() this if you want to insert the image directly in HTML tags:
$png = $obj->pngGeneratorFuntion(1,30,'blank');
echo '<img src="data:image/png;base64,'.base64_encode($png).'">';
But it's not a good solution to insert image data directly into HTML
You can make a separate file image_process.php and send the data to that file with $_GET parameters and return image content. Then you can use:
<img src="image_process.php?text=ImageText" alt="" />