Forum Moderators: coopster

Message Too Old, No Replies

Problem exporting to Excel(xls)

         

dreeves

8:25 pm on Mar 15, 2010 (gmt 0)

10+ Year Member



I am having trouble using PHP to export some data to a table. After I am prompted if I want to Open or Save the file (and click open) I receive an error message stating:"The file you are trying to open is in a different format than specified by the file 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 click "yes" and the file opens just fine.

How can I prevent this error message from coming up? What is causing it in the first place? I'm guessing it is something in the header.

<?php
include 'dbinfo.inc.php';
$link= mysql_connect('localhost',$username,$password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
@mysql_select_db($grant_database) or die( "Unable to select database");

$Result = $pDate = null;

$Query = "SELECT * from main LIMIT 0,20";

$Result = mysql_query($Query);

// For Headings in Excel
$contents="Project Number\tProject Name\tGrant Year\tProject Description\n";

// Put data records from mysql by while loop.
if($Result)
{
while($Row=mysql_fetch_array($Result)){

$contents.=$Row['project_number']."\t";
$contents.=$Row['project_name']."\t";
$contents.=$Row['grant_year']."\t";
$contents.=$Row['project_description']."\n";
}
}

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-Type: application/octet-stream"); //I tried vnd.ms-excel and it still didn't work
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=orderlist.xls ");
header("Content-Transfer-Encoding: binary ");

print_r($contents);
exit;

?>

Matthew1980

8:49 pm on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Dreeves,

I'm not too experienced with this area of php but a quick google search found this for me:-


header("Content-Type: application/excel");


As the other version just means binary safe, and the mime type listed for that is .zoo, which incidentally I have never heard of ;-p

Im not saying as this will work, but at least the browser will know whats coming :)

Also, IMHO it's not good to suppress the error messages ie: @mysql_..... if anything, the more info that you can get the better!

[EDIT] Though, depending on how you phrase the question you get different results ;-p I double checked that one!

Good Luck!

Cheers,
MRb