PHP import Excel into database (xls & xlsx)

PHP import Excel into database (xls & xlsx)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP import Excel into database (xls & xlsx)

Importing data from Excel files into a MySQL database is a routine requirement for many backend applications, often triggered by manual exports or bulk data migrations. The core challenge lies in parsing the binary format of .xls or .xlsx files and safely mapping that structure to relational tables without compromising security or performance.

Historically, developers have relied on older libraries like php-excel-reader, which was hosted on Google Code before moving to GitHub. This library is capable of displaying Excel content as HTML, a feature useful for debugging but perhaps overkill if your goal is strictly data ingestion. A common misconception is that simply reading the file into an array and executing a raw SQL statement is sufficient. While technically possible for small datasets, this approach introduces significant risks regarding memory consumption and SQL injection vulnerabilities when handling user-uploaded files.

For modern PHP environments, particularly within the Laravel ecosystem, you should avoid writing your own parsers or relying on legacy libraries that lack active maintenance. Instead, leverage robust packages designed specifically for data binding. Libraries such as phpoffice/phpspreadsheet are the industry standard because they handle both .xls and .xlsx formats natively without requiring external dependencies like PHP-Excel (the older EOL library).

Reading the Spreadsheet into Arrays

The most straightforward implementation pattern involves using a package to read the file and return data in an iterable array structure. This decouples the parsing logic from your database layer, allowing you to validate the data before writing it.

Here is how you might utilize PhpOffice\PhpSpreadsheet to extract rows:

use PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = IOFactory::load('path/to/file.xlsx');
$worksheet = $spreadsheet->getActiveSheet();

// Iterate through rows and columns to build an array of records
$data = [];
foreach ($worksheet->getRowIterator() as $row) {
    $cellIndex = 0;
    foreach ($row->getCellIterator() as $cell) {
        if ($cell->getValue() === null && $cell->getDataType() !== \PhpOffice\PhpSpreadsheet\Cell\DataType::STRING) {
             // Handle empty cells appropriately, e.g., default to NULL or empty string
             continue; 
        }
        $data[] = [
            'column_' . ($cellIndex + 1) => $cell->getValue()
        ];
        $cellIndex++;
    }
}

This approach gives you full control over the data transformation phase. You can trim whitespace, cast values to integers or dates, and filter out rows that don't meet your criteria before any database interaction occurs.

Writing to MySQL Safely

Once the data is in memory, executing a single massive INSERT statement is generally discouraged due to query length limits and potential timeout issues. Instead, use prepared statements with batch inserts. In Laravel, you can utilize the Eloquent ORM or raw queries with binding parameters to ensure safety.

// Example using Laravel's bulk insert capability (Laravel 8+)
foreach ($data as $row) {
    // Map column names from keys to actual table columns
    $record = [
        'name' => $row['column_1'],
        'email' => $row['column_2'],
        // ... other fields
    ];

    Database::table('users')->insert($record);
}

Alternatively, for higher performance with large datasets, consider using DB::transaction() to wrap the batch insert in a single atomic operation, or utilizing Laravel's chunk method if you were iterating from a database rather than a file. However, since you are reading from a file, loading chunks into memory and inserting them in batches of 500 to 1000 is often the sweet spot between speed and RAM usage.

Critical Trade-offs and Pitfalls

The primary pitfall when importing Excel files is data integrity. Excel allows users to input formulas, hidden rows, or merged cells that do not translate well to a flat database schema. A merged cell in Excel represents a single value visually but spans multiple physical cells; if you parse strictly by grid position, you may duplicate data or lose values entirely. Always validate that your parser handles merged cells according to your specific business logic.

Furthermore, memory usage scales linearly with the number of rows processed. If you attempt to load a 100MB Excel file into an array and then process it all at once, you risk exhausting the PHP memory_limit. Streaming the file or processing it in chunks is essential for production-grade scripts handling large datasets.

While specific tutorials might suggest using older tools found on legacy sites like [https://laravelcompany.com], always verify that the underlying libraries support the version of PHP and extensions (like zip, xml, or bcmath) required by your environment. Modern solutions reduce friction by abstracting these low-level details, allowing you to focus on data validation rather than binary parsing logic.

Our network