Export data feature is very useful where the data is saved on the local drive for offline uses. Export data to file functionality provides a user-friendly way to maintain a large number of data in the web application. There are various file formats are available to export data and download it as a file. Microsoft Excel is a widely used spreadsheet format that organizes and maintains data.
Generally, export data functionality is used in the data management section of the web application. Excel is the best format to export data in a file and you can easily export data to excel using PHP. In this tutorial, we will show you how to export data to Excel in PHP.
The example PHP 8 export Excel script lets you integrate export data to excel functionality. With one click, the user can export data from the MySQL database to Excel and download it in MS Excel file format (.xls/.xlsx).
In this example script, we will export data from the array (defined in the script) to an excel file.
The $data variable holds the data in array format which will be exported to Excel using PHP:
$data = array(
array("NAME" => "John Doe", "EMAIL" => "john.doe@gmail.com", "GENDER" => "Male", "COUNTRY" => "United States"),
array("NAME" => "Gary Riley", "EMAIL" => "gary@hotmail.com", "GENDER" => "Male", "COUNTRY" => "United Kingdom"),
array("NAME" => "Edward Siu", "EMAIL" => "siu.edward@gmail.com", "GENDER" => "Male", "COUNTRY" => "Switzerland"),
array("NAME" => "Betty Simons", "EMAIL" => "simons@example.com", "GENDER" => "Female", "COUNTRY" => "Australia"),
array("NAME" => "Frances Lieberman", "EMAIL" => "lieberman@gmail.com", "GENDER" => "Female", "COUNTRY" => "United Kingdom")
);
The filterData() function is used to filter string before added to the excel sheet row:
function filterData(&$str){
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
The following code helps to export data in excel and download it as a file using PHP.
$fileName variable defines the name of the excel file.$data array.$flag variable.filterData() function.// Excel file name for download
$filename = "data_export_" . date('Ymd_His') . ".xls";
// Headers for download
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;
In this example script, we will export data from the MySQL database to an excel file using PHP.
Create Database Table:
For this example, we will create a members table in the MySQL database from which data will be exported to Excel.
Here is the SQL statement to create a new MySQL table named members with the specified fields:
CREATE TABLE members (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
gender ENUM('Male', 'Female', 'Other') DEFAULT NULL,
country VARCHAR(50) NOT NULL,
created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
status TINYINT(1) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Field Details:
Database Configuration (dbConfig.php):
Create a new file named dbConfig.php to store the database connection configuration.
DB_HOST), username (DB_USER), password (DB_PASS), and name (DB_NAME) as per your database credentials.<?php
// Database configuration - update these values to match your environment
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'codexworld_db');
// Create a new mysqli connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Check connection
if ($conn->connect_error) {
// In production, avoid echoing raw errors. Log them instead.
die('Database connection failed: ' . $conn->connect_error);
}
?>
Export Data from Database:
Create a new file named index.php to export data from the MySQL database and download it as an excel file using PHP.
filterData() function is used to filter string before added to the excel data row.$filename – Define the name of the excel file to be downloaded.$fields – Define the column named of the excel sheet.$excelData – Add the first row to the excel sheet as a column name.<?php
// Include database configuration file
require_once 'dbConfig.php';
// Filter the excel data
function filterData(&$str){
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// Excel file name for download
$filename = 'members_export_' . date('Ymd_His') . '.xls';
// Column names
$fields = array('ID', 'NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
// Display column names as first row
$excelData = implode("\t", array_values($fields)) . "\n";
// Query to fetch records from database
$sql = "SELECT id, first_name, last_name, email, gender, country, created, status FROM members ORDER BY id ASC";
$result = $conn->query($sql);
// Output each row of the data
if ($result && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$status = $row['status'] == 1 ? 'Active' : 'Inactive';
$name = trim($row['first_name'] . ' ' . $row['last_name']);
$lineData = array($row['id'], $name, $row['email'], $row['gender'], $row['country'], $row['created'], $status);
array_walk($lineData, 'filterData');
$excelData .= implode("\t", array_values($lineData)) . "\n";
}
}
// Headers for download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
// Render excel data
echo $excelData;
// cleanup
if ($result) $result->free();
$conn->close();
exit;
?>
The above-mentioned solution helps you export data from the database to Excel and save it as a .xls file. If you want to export to Excel in an XLSX file, use the following process.
In this example script, we will export data from the MySQL database in an excel file using PHP and save it as a .xlsx file.
PHP XLSX Generator Library (PhpXlsxGenerator.class.php):
The PhpXlsxGenerator class handle the Excel file generation process and export data in a .xlsx file using PHP.
Note that: All the required files including this PhpXlsxGenerator library are included in our source code, you do not require to install it separately.
Export Data from Database to Excel in PHP:
The following code will export data from the MySQL database and download it as an excel file (.xlsx) using PHP.
<?php
// Include database configuration file
require_once 'dbConfig.php';
// Include XLSX generator library
require_once 'PhpXlsxGenerator.class.php';
// Excel file name for download
$filename = 'members_export_' . date('Ymd_His') . '.xlsx';
// Define header row
$excelData[] = array('ID', 'NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
// Query to fetch the same fields used in the UI
$sql = "SELECT id, first_name, last_name, email, gender, country, created, status FROM members ORDER BY id ASC";
$result = $conn->query($sql);
// Add row's data to excel data array
if ($result && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$status = $row['status'] == 1 ? 'Active' : 'Inactive';
$name = trim($row['first_name'] . ' ' . $row['last_name']);
$lineData = array($row['id'], $name, $row['email'], $row['gender'], $row['country'], $row['created'], $status);
$excelData[] = $lineData;
}
}
// Export data to excel and download as xlsx file
$xlsx = CodexWorld\PhpXlsxGenerator::fromArray( $excelData );
$xlsx->downloadAs($filename);
// cleanup
if ($result) $result->free();
$conn->close();
exit;
?>
If you want to save XLSX file on the server instead of downloading it, use the saveAs() method of PhpXlsxGenerator class.
$xlsx->saveAs('members-data.xlsx');
Export HTML Table Data to Excel using JavaScript
If you want to add an export option to the data list, the export to excel feature is perfect for it. With the export option, the user can download the data in an excel file and save it in a local drive. You can use this simple PHP 8 export Excel code to add export data functionality in the web application using PHP.
Download the complete source code from Download Source Code button below.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
Hi, my question is similar to Philip Beekman’s one: the Class seems to be capable of formatting the cells in many ways.
E.G. I wanted to align a cell content to the right, and I managed to do it, but only after digging in the Class (which I am not good at usually).
Is there any comprehensive documentation summarizing all these possibilities with examples?
The code shown in the YT video tutorial outputs wonderfully formatted cells with proper widths and alignments, but I can’t see any explicit info about how to get that result in the HTML. What (and where) am I missing? 🙂
Thanks!
Your script is nice and works well. Thank you.
Is it possible to add WrapText to a cell or column? It looks like your code is prepaared to do this, Could you give an example?
Hello.
Very well PHPXLSXGENERATOR,
but is possible to orientation page in LANDSCAPE?
Thanks.
Alessio
Great script, for excel file writing without any complexity, this script is the best, no dependencies, it just works, and also works great with UTF-8!
Congratulations and thank you!
Your class is the FIRST thing that -actually- worked for me, seamlessly dealing with html links and utf-8. So mine is just a BIG “thank you!”
Thank you so much for this
How to white space pre line in excel when export ( data in textarea) please?
I am unable to export file extension as .xlsx , it only working to .xls format. Can you please suggest what are changes required to export file as .xlsx format. Thanks in advance
hi,the code worked for me, but the problems is data limitation, how can i force the code to download all data
Hello,
the export in german xls kills or change the ÖÄÜß to it shows like àhow can i change this to get the öäü back in xls.
how i change to utf-8 become to another language
Hello,
so I downloaded php to excel source
Now my question is:
How to add new sheet in exported exccel file?
When i have mulltible data tables i need to show, each one should be in other different sheet. Can You please help me. Thanks a lot
Hi,
Very good.
Congratulations
Hi, this one works very well but want to ask is it possible to include images inside each row of the excel? I mean the data I want to export got images.
bro, thank you so much! it works perfectly.
Thank you Codexworld… this code worked very well for me… Wel Done!!!
Is there a way to set the size of the cells?
Hi CODEXWORLD,
I just want to thank you for sharing the knowledge or code with us. You guys are awesome and all your code snippet are awesome, easily understandable and fully working. This website is always my favorite website. I also recommend my colleague and friends to visit your website whenever they need help. You guys are awesome.
could you just comment on the code please
Hi
how to increase column width when export excel…
pls help me on.
Awesome Script!! Is there a way to set the size of the cells?? Thank you
Hi and thank you for this snippet.
Can you please help me on how to export a table to an array?