Categories
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

<< May, 2013 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
262728293031
Search Blog

Recent Comments
Re: Disappearing IE Popup Window During Save/Open Dialog (by LZ at 4/20 7:58 AM)
Re: Create Dynamic WHERE Clauses in PHP (by pooja at 3/20 7:29 AM)
Re: Just What IS a 'Service Layer', Anyway? (by EugenK at 3/07 7:56 PM)
Re: Using Google as your CF Mail Server (by 5starwebteam.com at 2/25 1:27 AM)
Re: Why Provide for Service layer objects in CFWheels? (by Steven Benjamin at 1/25 11:43 AM)
Re: What is an 'Advanced' Coldfusion Developer? (by ColdFusion Developer at 12/24 5:14 AM)
Re: Equivalent of SQL "TOP X" in Oracle (by Ashenafi Desalegn at 12/06 5:29 AM)
Re: PHP Export to Excel Snippet (by serene at 12/05 1:44 AM)
Re: Just What Is 'Application Logic', Anyway? (by Arif at 11/13 8:06 AM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Aaron at 10/22 2:31 PM)
Re: PHP Export to Excel Snippet (by Jafar Shah at 10/10 4:28 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Chenelle S at 10/04 12:53 PM)
Re: PHP Export to Excel Snippet (by Kilo at 9/26 5:20 PM)
Re: Porting Coldfusion Code to Mura (by tariq at 9/03 9:51 AM)
Re: Just What IS a 'Service Layer', Anyway? (by James at 8/27 4:06 PM)
Re: Calculating Business Hours (by helen at 8/14 2:54 AM)
Re: What IS 'Business Logic', Anyway? (by dougboude at 8/06 11:30 AM)
Re: What IS 'Business Logic', Anyway? (by Adrianne at 8/06 10:29 AM)
Re: Family Law: The Weapon of Choice for Woman Scorned (by dougboude at 8/04 4:39 PM)
Re: Family Law: The Weapon of Choice for Woman Scorned (by Lola LB at 8/04 7:43 AM)
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

30 June 2009
PHP Export to Excel Snippet

For those PHPers out there who are doing an export to Excel, I thought I'd share the solution I came up with. I realize there are already a gabillion examples out there, but I merged some of the better approaches from a few of them that made it fairly elegant, I think (such as leveraging the implode, array_keys, and array_values functions).

Without further adieux...

<?php
//your code here to create your sql statement...we'll call it $finalSQL
 
//go get the data we need...
$Result=mysql_db_query($DBName,$finalSQL,$Link);
//fetching each row as an array and placing it into a holder array ($aData)
while($row = mysql_fetch_assoc($Result)){
 $aData[] = $row;
}
//feed the final array to our formatting function...
$contents = getExcelData($aData);

$filename = "myExcelFile.xls";

//prepare to give the user a Save/Open dialog...
header ("Content-type: application/octet-stream");
header ("Content-Disposition: attachment; filename=".$filename);

//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file
$expiredate = time() + 30;
$expireheader = "Expires: ".gmdate("D, d M Y G:i:s",$expiredate)." GMT";
header ($expireheader);

//output the contents
echo $contents;
exit;
?>

<?php
 function getExcelData($data){
    $retval = "";
    if (is_array($data)  && !empty($data))
    {
     $row = 0;
     foreach(array_values($data) as $_data){
      if (is_array($_data) && !empty($_data))
      {
          if ($row == 0)
          {
              // write the column headers
              $retval = implode("\t",array_keys($_data));
              $retval .= "\n";
          }
           //create a line of values for this row...
              $retval .= implode("\t",array_values($_data));
              $retval .= "\n";
              //increment the row so we don't create headers all over again
              $row++;
       }
     }
    }
  return $retval;
 }
?>

 

 




Posted by dougboude at 1:06 PM | PRINT THIS POST! |Link | 13 comments
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: PHP Export to Excel Snippet
Great script! Thanks for posting. I am curious why the exports all begin on row 11 in Excel for me as opposed to row 1. Any ideas? Thanks again...this is great.

Tom
Posted by tomw on November 25, 2009 at 1:45 PM

Re: PHP Export to Excel Snippet
this script generated double column for each entry so if table contain 3 column then excel file will ocntain 6 olumn
sorry for bad typing
Posted by susheel on February 1, 2010 at 5:54 AM

Re: PHP Export to Excel Snippet
reply me at my email : sushe3l@gmAIL.COM
Posted by susheel on February 1, 2010 at 6:06 AM

Re: PHP Export to Excel Snippet
that's the best code i have come across so far that walks the talk.Thanks!
Posted by james on April 17, 2010 at 4:28 AM

Re: PHP Export to Excel Snippet
"foreach(array_values($data) as $_data)" is too complicated. "foreach($data as $_data)" will suffice.
Posted by bob on May 25, 2010 at 2:12 PM

Re: PHP Export to Excel Snippet
It is a wonderful snippet.
However, on Excel 2007, it generated a warning message: "The file you are trying to open, is in a different format than specified by the extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

I did open the file and needed to save it in version 2007 xlsx format.

Ben
Posted by Ben Lam on May 6, 2011 at 1:15 PM

Re: PHP Export to Excel Snippet
I'm getting the following error. Any suggestions?

Access denied for user 'loanmod1'@'localhost' (using password: NO)
Posted by Denise Cowen on July 4, 2011 at 3:09 PM

Re: PHP Export to Excel Snippet
@Denise,

My best guess based on what you shared is that your query is failing due to a permissions issue. I would look at the database link you're creating and make sure the credentials are correct. Make sense?

Doug
Posted by dougboude on July 5, 2011 at 9:29 AM

Re: PHP Export to Excel Snippet
that's Gr8 i am really thankful to u
and if possible then plz inform me about export to pdf
Posted by Ashish Sharma on September 10, 2011 at 4:13 AM

Re: PHP Export to Excel Snippet
what about styling the sheet? any ideas?
Posted by rasha on January 10, 2012 at 1:55 AM

Re: PHP Export to Excel Snippet
Re: PHP Export to Excel Snippet
Great script! Thanks for posting. I am curious why the exports all begin on row 11 in Excel for me as opposed to row 1. Any ideas? Thanks again...this is great.

Tom

---
Any blank lines outside of your tags will add a line to excel.
For Example the below would start with "title" on row 4 of excel due to the 3 blank lines above the word title:
some code here
?>



Title
some more code
?>
Posted by Kilo on September 26, 2012 at 5:20 PM

Re: PHP Export to Excel Snippet
Gr8 example... it has helped me in getting what I want. Thanks for sharing !!
Posted by Jafar Shah on October 10, 2012 at 4:28 AM

Re: PHP Export to Excel Snippet
Thanks for sharing with us. :)
Posted by serene on December 5, 2012 at 1:44 AM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

Five plus Twelve equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!