i have a website with one simple function to generate an excel with array data and then offers user to download.
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
the code above was used to test, but I only get some html code from the website in the excel, not the data.
May I ask why it happens?
Thanks!
Make sure you don't send anything before header calls.
// At the begginnig of script...
ob_start();
// ... do some stuff ...
ob_get_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
die();
Another approach if you need to process entire script:
<?php
// At the beggining...
ob_start();
$content="";
$normalout=true;
// ... do some stuff ...
// i guess if some condition is true...
$content=ob_get_clean();
$normalout=false;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
// Here you could die() or continue...
ob_start();
// ... rest of execution ...
$content.=ob_get_clean();
if($normalout)
{
echo($content);
} else {
// Excel provided no output.
}
?>
This should work.
That code seems to work on Chrome without any issue (using php tags, of course).
Here you have a template, anyway, that I use for exporting POST tables that are being sent.
<?php
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
$date = date('Y-m-d-Hi');
header("content-disposition: attachment;filename=Excel_Report_$date.xls");
$table = $_POST["table_info"];
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<tr><th> </th></tr>
<tr><td> </td></tr>
<?=$table?>
</table>
</body>
</html>
If you are exporting some reports that would require some more detail, I would recommend PHPExcel as by far the best library out there for CSV/XML/XLS(X) management via PHP code.
You are sending a file that is a tab-sepparated values, not an XLS (which is a binary format).
What you can do is send the file as a CSV (Content-type="text/csv"), and the file formatted as csv:
header("Content-Type: text/csv");
header("content-disposition: attachment;filename=my_document.csv");
echo '"First Name";"Last Name";"Phone"' . "\n";
echo '"John";"Doe";"555-123456"' . "\n";
Related
First, I have a few knowledge in PHP, and that is all I could do with my excel export (see attached code below)
It works, but I want to export that excel file with 2 more sheets, I've googled a lot but could not customize the code to insert in it, please, help me if you can
Thank you
<?php
$filename = time().".csv";
header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename='.$filename);
ExportFile1($main_exce);
function ExportFile1($records) {
$do = false;
if(!empty($records)){
foreach($records as $down){
$heading = true;
foreach($down as $row) {
if($heading) {
// display field/column names as a first row
$heading = false;
if(!$do){
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
$do = true;
}
}else{
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
// $d = "\t\n\t\n\t\n";
// print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
}
exit;
?>
The reason you can't make this work is that you are not creating an Excel export here.
You're creating a plain-text, tab-delimited file. Excel can import files in that format, but it's not a true Excel file. It's a simple flat file, and as such, it doesn't support multiple worksheets, unlike a real Excel file.
If you want to solve this, you need to rewrite this code so that it outputs a file which is in the real Excel file format - it's considerably more complex than a tab-delimited text format. There are various libraries available for PHP which can help you easily create real Excel files in xlsx format. Recommendations are off-topic here but they are not hard to find using a search engine.
I have PHP saving an output file all from one very long string. I want this code that is being outputted to be formatted properly, so I am trying to add linebreaks in at certain points.. I have been trying to use "\n", but for some reason that is not doing the trick.. Here's the relevant code:
foreach($headerColumn as $hColumn) {
$outputString .= '<td>' . $hColumn . '</td>' . "\n";
};
Here I have the "\n" added to the end of the string, but for some reason it is being outputted like this:
<thead>
<tr><td>Name</td><td>Ticker</td><td>Buy Date</td><td>Current Yield</td>
</tr>
</thead>
When, in actuallity, I want each on its' own line.. any ideas? in case it has something to do with the content type of the file, here is my file write call:
header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($outputString));
header('Connection: close');
echo $outputString;
Thanks!
I think what you want to use is PHP_EOL:
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2
So, for your example:
$outputString .= '<td>' . $hColumn . '</td>' . PHP_EOL;
I don't know if this is the best practice... but you can actually put a newline into the code by simply not ending the string quotation until the next line:
foreach($headerColumn as $hColumn) {
$outputString .= '<td>' . $hColumn . '</td>' . "
";
};
I am trying to generate the force download excel file in my Tidesdk app.So i am trying the following code to work, but it is not working properly.So guys please help me to find out the solution.
<?php
header ("Content-type: application/octet-stream");
header( "Content-disposition: attachment; filename=sheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'Maddy' . "\t" . 'Shan' . "\t" . '555-4445' . "\n";
?>
Just remove
<?php
and
?>
and you should be good to go !
Attempting to print out an image to the browser using code I copied from http://php.net/manual/en/function.imagecopyresampled.php.
It prints out a box of random characters.
CODE:
public function printSummaryArticle($article, $copy, $thumb) {
$src_image = Config::getAbsPath() . '/images/articles/' . $article['image'];
echo
'<div class="summary_article"><a href="/'
. BreadCrumbs::getCrumb(1)
. '/'
. BreadCrumbs::getCrumb(2)
. '/article/'
. $article['id']
. '"><h4>'
. $article['title']
. '</h4></a> ('
. $article['date']
. ')'
. '<img src="data:image/jpeg;base64,'. imagejpeg($thumb->generateThumb($src_image, 300, 200)) . '"'
. '<p>'
. strip_tags($copy->truncateString($article['body'], 250, " "))
. '</p><p><a href="/' . BreadCrumbs::getCrumb(1)
. '/'
. BreadCrumbs::getCrumb(2)
. '/article/'
. $article['id']
. '"> Read more</a></p></div>';
}
Also tried:
public function printSummaryArticle($article, $copy, $thumb) {
$src_image = Config::getAbsPath() . '/images/articles/' . $article['image'];
echo
'<div class="summary_article"><a href="/'
. BreadCrumbs::getCrumb(1)
. '/'
. BreadCrumbs::getCrumb(2)
. '/article/'
. $article['id']
. '"><h4>'
. $article['title']
. '</h4></a> ('
. $article['date']
. ')';
header('Content-type: image/jpeg');
imagejpeg($thumb->generateThumb($src_image, 300, 200));
echo
'<p>'
. strip_tags($copy->truncateString($article['body'], 250, " "))
. '</p><p><a href="/' . BreadCrumbs::getCrumb(1)
. '/'
. BreadCrumbs::getCrumb(2)
. '/article/'
. $article['id']
. '"> Read more</a></p></div>';
}
Same result. except with an added error claiming headers have already been sent.
How can I fix this?
imagejpeg() neither returns a string nor performs Base64 encoding. To work around this, capture its output in a PHP output buffer, and then Base64 encode the captured output:
ob_start();
imagejpeg( $my_img );
echo '<img src="data:image/jpeg;base64,' . base64_encode(ob_get_clean()) . '">';
Note that data: URLs are limited to 32 KB in Internet Explorer 8 and do not work in earlier versions of IE (source). If you need to support IE 8 and below, you may want to instead save the image as a separate file on the server. This is left as an exercise for the reader :)
(For an explanation of the "Headers already sent" warning, see How to fix "Headers already sent" error in PHP.)
You haven't closed the image tag, but more importantly you haven't base64_encoded the image data
Before you echo that string
ob_start();
imagejpeg($thumb->generateThumb($src_image, 300, 200));
$imagejpg=ob_get_clean();
then this
. '<img src="data:image/jpeg;base64,'
. base64_encode($imagejpg)
. '" />'
You can't do what you're trying to do in the 2nd example
I am trying to add data into excel file which is extracted from wordpress database, Actually I am trying to export data (tags) from database into excel file. And I write down a code, but when I click on generate button. This generates empty file.
Please guys check what I am doing wrong.
Codes are below:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
if ( $count > 0 )
{
echo 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
echo $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
echo $xls_file;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
exit();
}
The above codes are not writing data into excel file. please check and let me know.
Just based on your existing code:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
$xls_file = '';
if ( $count > 0 )
{
$xls_file .= 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
$xls_file .= $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
echo $xls_file;
exit();
}
A more general suggestion, not a solution for your coding problem: create an HTML table file from the code and then open it in Excel for conversion. Doing it so you'll have a better understand on what's going on with your code: you can add var_dumps or simply debug it like a normal web page.
Having an html table is also useful because excel works quite well in converting it to XLS files.
After your HTML file works well, then you can apply necessary formatting/header to the code in order to create the xls file from scratch.