0

I am trying to create an html file which it will have a download button. I found a php code to export mysql database to an excel file.

PHP code :

<html><head><title>MySQL Table Viewer</title></head><body>
<?php
/***** EDIT BELOW LINES *****/
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "admin"; // MySQL Username
$DB_Password = ""; // MySQL Password
$DB_DBName = "login"; // MySQL Database Name
$DB_TBLName = "logintable"; // MySQL Table Name
$xls_filename = 'export_'.date('Y-m-d').'.xls'; // Define Excel (.xls) file name

/***** DO NOT EDIT BELOW LINES *****/
// Create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
// Execute query
$result = @mysql_query($sql,$Connect) or die("Failed to execute query:<br />" . mysql_error(). "<br />" . mysql_errno());

// Header info settings
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");

/***** Start of Formatting for Excel *****/
// Define separator (defines columns in excel &amp; tabs in word)
$sep = "\t"; // tabbed character

// Start of printing column names as names of MySQL fields
for ($i = 0; $i<mysql_num_fields($result); $i++) {
  echo mysql_field_name($result, $i) . "\t";
}
print("\n");
// End of printing column names

// Start while loop to get data
while($row = mysql_fetch_row($result))
{
  $schema_insert = "";
  for($j=0; $j<mysql_num_fields($result); $j++)
  {
    if(!isset($row[$j])) {
      $schema_insert .= "NULL".$sep;
    }
    elseif ($row[$j] != "") {
      $schema_insert .= "$row[$j]".$sep;
    }
    else {
      $schema_insert .= "".$sep;
    }
  }
  $schema_insert = str_replace($sep."$", "", $schema_insert);
  $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
  $schema_insert .= "\t";
  print(trim($schema_insert));
  print "\n";
}
?>
</body></html>

Now the results of the file when i open it in the browser is :

username password flag counter admin pass1 1 1 admin2 pass2 0 2

It doesn't create any excel file(or i can't find it) and I'd like to call this php from a html file which it will has a download button for the excel file.

pnuts
  • 58,317
  • 11
  • 87
  • 139
NickName
  • 313
  • 2
  • 9
  • 25
  • This script seems to generate the excel file itself, you might want to add headers so that it's presented as a download for the user. Have a look at http://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header for example. – ErikL Mar 12 '15 at 10:13
  • You're generating a CSV file rather than an Excel file, so why don't you use PHP's built-in [fputcsv()](http://www.php.net/manual/en/function.fputcsv.php) function to eliminate a lot of that homebrew code which doesn't really create a correct CSV file anyway – Mark Baker Mar 12 '15 at 10:18
  • actually, I just tested your script, and it works right away when opening it in chrome. – ErikL Mar 12 '15 at 10:30
  • What do you mean? I wrote the output of browser... I can't find the excel... or how to download it... – NickName Mar 12 '15 at 11:03
  • the "excel" is on your screen, "username password flag counter" are the headers in your table. Apparently your browser doesn't recognize it as a download and shows it to you as-is. As mentioned by Mark, it's not even a actual excel file, it's just a csv-ish file. – ErikL Mar 12 '15 at 11:44
  • My problem then is how to make it an excel file and be available to downoload it? – NickName Mar 12 '15 at 11:59
  • 1
    Well `application/xls` isn't a valid mime type.... the valid mime type for a csv file (such as you're creating) is `text/csv`; the mime type for a BIFF-formal xls file is `application/vnd.ms-excel` – Mark Baker Mar 12 '15 at 12:19

1 Answers1

0

You can try this script: https://github.com/elidickinson/php-export-data
It's easy to use and creates file for download using headers

Sample:

// When executed in a browser, this script will prompt for download 
// of 'test.xls' which can then be opened by Excel or OpenOffice.

require 'php-export-data.class.php';

// 'browser' tells the library to stream the data directly to the browser.
// other options are 'file' or 'string'
// 'test.xls' is the filename that the browser will use when attempting to 
// save the download
$exporter = new ExportDataExcel('browser', 'test.xls');

$exporter->initialize(); // starts streaming data to web browser

// pass addRow() an array and it converts it to Excel XML format and sends 
// it to the browser
$exporter->addRow(array("This", "is", "a", "test")); 
$exporter->addRow(array(1, 2, 3, "123-456-7890"));

// doesn't care how many columns you give it
$exporter->addRow(array("foo")); 

$exporter->finalize(); // writes the footer, flushes remaining data to browser.

exit(); // all done

?>
Jafar Akhondali
  • 1,552
  • 1
  • 11
  • 25