CharlesWashington
CharlesWashington

Reputation: 109

Save MySQL data to Excel sheet using PHP

I am trying to write data from database to a downloadable excel sheet. The code is working in the sense that it downloads the file with the desired name. However if I open the Excel sheet the cells are empty and my data is not in the sheet.

Here is my code

require_once('include/connect_pdo.php');
$myschool = $_POST['country'];

$findschool = $conn->prepare("SELECT Query");
$findschool->execute();

$filename = "Name"; 
$file_ending = "xls";

//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename= $filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");

/*******Start of Formatting for Excel*******/   

//define separator (defines columns in excel & 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";
}   

Upvotes: 0

Views: 106

Answers (2)

CharlesWashington
CharlesWashington

Reputation: 109

This sorted my problem.

Header('Content-Description: File Transfer');
Header('Content-Encoding: UTF-8');
Header('Content-type: text/csv; charset=UTF-8');
Header('Content-Disposition: attachment; filename=' . '$filename' . '.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM

$output = fopen("php://output", "w");
fputcsv($output, array('Number1', 'Number 2'));
$findschool = $conn->prepare("SELECT Query Here);
$findschool->execute();
while ($result = $findschool->fetch(PDO::FETCH_ASSOC)) {

fputcsv($output, $result);  
}
fclose($output);

Upvotes: 1

Jiri Kapoun
Jiri Kapoun

Reputation: 300

XLS is Microsoft's proprietary binary format. What you create with your PHP code is a CSV file. Try changing your file extension to .csv and Content-Type header to text/csv.

Upvotes: 0

Related Questions