Download to excel issue

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ady01
Forum Newbie
Posts: 1
Joined: Tue May 27, 2008 10:03 am

Download to excel issue

Post by Ady01 »

Hope some one can help here as this ones getting me stumped, I have the below code and what i want it to do is take data from mysql table and download the data to an excel file which the user gets the option to download or open it, when i run the below code all i get is the output in the browser window not in excel like i want ? can anyone help .. ? (by the way i cant use pear)

Code: Select all

 
<?php
 
include('config.php');
 
mysql_connect($AddressBook_HOST, $AddressBook_Username, $AddressBook_Password) or die ("Can't connect!"); 
mysql_select_db($AddressBook_DatabaseName) or die ("Can't open database!");
 
$result = mysql_query('select * from Addresses');
$count = mysql_num_fields($result);
 
for ($i = 0; $i < $count; $i++){
    $header .= mysql_field_name($result, $i)."\t";
}
 
while($row = mysql_fetch_row($result)){
  $line = '';
  foreach($row as $value){
    if(!isset($value) || $value == ""){
      $value = "\t";
    }else{
 
      $value = str_replace('"', '""', $value);
 
      $value = '"' . $value . '"' . "\t";
    }
    $line .= $value;
  }
  $data .= trim($line)."\n";
}
 
  $data = str_replace("\r", "", $data);
 
 
if ($data == "") {
  $data = "\nno matching records found\n";
}
 
 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=excelfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
 
echo $header."\n".$data; 
?> 
 
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Download to excel issue

Post by John Cartwright »

Code: Select all

header("Content-Type: application/force-download");
you need to send this header as well to prompt the download dialogue
Post Reply