How to Read Data from Excel File in PHP

Cody Schneider8 min read

Reading data from an Excel file is a surprisingly common task when building a web application. You might need to import a product list, process user data from an upload, or sync information from a spreadsheet into your database. While it might seem complex, the right tools make it a manageable process. This tutorial will walk you through exactly how to read data from an Excel file in PHP, step-by-step.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Why Bother Reading Excel Files with PHP?

Before diving into the code, it helps to understand the common scenarios where this skill is useful. You're not just learning a neat trick, you're enabling powerful features for your projects:

  • Data Imports: Allowing non-technical users to upload and import data in a familiar format like Excel. Think of an e-commerce store owner uploading their entire product catalog in one go.
  • Bulk Updates: Processing a spreadsheet of changes to update thousands of records in your database at once, saving hours of manual entry.
  • Reporting: Ingesting data from an existing Excel-based reporting process to display it on a web dashboard.
  • System Integration: Pulling data from legacy systems or an external service that outputs information in .xlsx format.

In all these cases, manually copying and pasting is slow and prone to errors. Automating the process with PHP is the efficient and professional solution.

The Challenge: An Excel File Isn't Just Text

If you've ever worked with CSV files in PHP, you might be tempted to use functions like fopen() or file_get_contents(). Unfortunately, that won't work for Excel files (.xlsx or .xls).

Unlike a simple CSV file, which is just comma-separated plain text, an .xlsx file is actually a compressed ZIP archive. Inside this archive are multiple XML files and folders that define the document's structure, content, formatting, images, and more. Trying to parse this complex structure manually would be a nightmare.

This is why we need a specialized library. A good library handles all the complexity of unzipping the archive and parsing the XML for you, giving you a simple way to access the data cell by cell.

Introducing PhpSpreadsheet: The Modern Solution

For years, the go-to library was called PHPExcel. However, it's no longer maintained and has been officially replaced by its successor: PhpSpreadsheet.

PhpSpreadsheet is a powerful, modern library that can both read and write a variety of spreadsheet formats, including:

  • Excel (.xlsx and the older .xls)
  • OpenDocument Spreadsheet (.ods)
  • CSV (.csv)
  • And several others

It can handle complex features like formulas, cell formatting, charts, and more. For our purpose of reading data, it does an excellent job of simplifying the process.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Setting Up Your Project

To get started, we first need to add PhpSpreadsheet to our project. The best way to manage PHP packages is with Composer. If you don't have it installed, you'll need to do that first.

Step 1: Install Composer (If you don't have it)

Composer is a dependency manager for PHP. It allows you to declare the libraries your project depends on, and it will manage (install/update) them for you. If you already have Composer set up, you can skip this step. If not, follow the official installation instructions on the Composer website for your operating system.

Step 2: Install the PhpSpreadsheet Library

Once Composer is ready, navigate to your project's directory in your terminal or command prompt and run the following command:

composer require phpoffice/phpspreadsheet

This command does two things:

  • It creates a composer.json file (if one doesn't exist) to keep track of your dependencies.
  • It downloads the PhpSpreadsheet library and all its required components into a vendor directory.

With that simple command, your project is now equipped to handle Excel files.

Reading an Excel File: Step-by-Step with Code

Now for the fun part. Let's create a PHP script that reads data from an Excel file named users.xlsx. Imagine this file has a simple list of users with a header row:

Example users.xlsx:

Create a new PHP file (e.g., read_excel.php) in the same directory as your vendor folder.

Step 1: Include Composer's Autoloader

The very first line in your script should be to include the autoload.php file generated by Composer. This file handles loading all the necessary library classes for you, so you don't have to write a bunch of include or require statements yourself.

<?php

require 'vendor/autoload.php',

Step 2: Use the IOFactory to Load the File

The IOFactory class in PhpSpreadsheet is a smart helper that automatically detects the file type (.xlsx, .xls, .csv, etc.) and uses the correct reader for it. This makes your code more flexible.

use PhpOffice\PhpSpreadsheet\IOFactory,

// Replace 'users.xlsx' with the path to your file
$spreadsheet = IOFactory::load('users.xlsx'),

Step 3: Get the Active Worksheet

An Excel workbook can contain multiple sheets. For this example, our data is on the first (and only) sheet. We can get this sheet using getActiveSheet().

// Get the first worksheet
$worksheet = $spreadsheet->getActiveSheet(),

If you knew the sheet's name, you could also get it this way:

$worksheet = $spreadsheet->getSheetByName('Sheet1'),
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step 4: Iterate Through Rows and Cells

Now we have access to the worksheet, we can loop through its rows to get the data. The goal is to read each row and then read each cell within that row.

Here is a complete script showing how to iterate, get the cell values, and print them out:

<?php

require 'vendor/autoload.php',

use PhpOffice\PhpSpreadsheet\IOFactory,

try {
    // Define the path to the Excel file
    $filePath = 'users.xlsx',

    // Load the spreadsheet file
    $spreadsheet = IOFactory::load($filePath),

    // Get the active worksheet
    $worksheet = $spreadsheet->getActiveSheet(),

    // Loop through all the rows in the worksheet
    foreach ($worksheet->getRowIterator() as $index => $row) {
        // Skip the first row if it's the header
        if ($index == 1) {
            continue,
        }

        echo "<p>Processing Row #{$index}</p>",
        echo "<ul>",

        // Loop through all the cells in the current row
        foreach ($row->getCellIterator() as $cell) {
            // Get the value of the cell
            $cellValue = $cell->getValue(),
            echo "<li>" . htmlspecialchars($cellValue) . "</li>",
        }

        echo "</ul>",
    }
} catch (\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
    die('Error loading file: ' . $e->getMessage()),
}

When you run this script, it will neatly print the data from each row, skipping the header. You would replace the echo statements with your own logic, such as inserting the data into a database.

More Practical Ways to Get Data

Iterating row by row gives you maximum control, but sometimes you need the data in a different format. Here are a couple of useful shortcuts.

Get All Data as an Array

If you're working with a smaller file and want to grab everything at once, toArray() is incredibly handy. It returns a simple, indexed array of all the data in the sheet.

<?php

require 'vendor/autoload.php',

use PhpOffice\PhpSpreadsheet\IOFactory,

$spreadsheet = IOFactory::load('users.xlsx'),
$worksheet = $spreadsheet->getActiveSheet(),

// Get worksheet data as a simple array
$dataArray = $worksheet->toArray(),

// Remove the header row
$header = array_shift($dataArray),

// Process the data
foreach ($dataArray as $row) {
    // $row is now a simple array like ['1', 'John', 'Doe', 'john.doe@example.com']
    print_r($row),
}
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Map Data Using Headers

A much more robust way to work with data is to map it to associative arrays using the header row as keys. This makes your code far more readable and less fragile, if the column order changes, your code won't break.

<?php

require 'vendor/autoload.php',

use PhpOffice\PhpSpreadsheet\IOFactory,

$spreadsheet = IOFactory::load('users.xlsx'),
$worksheet = $spreadsheet->getActiveSheet(),
$dataArray = $worksheet->toArray(),

// Get the header row and use it as keys
$header = array_shift($dataArray),
$header = array_map('strtolower', $header), // make headers consistent

$processedData = [],
foreach ($dataArray as $row) {
    $processedData[] = array_combine($header, $row),
}

// Now you have a clean list of associative arrays
print_r($processedData),

/*
Output would look like:
Array
(
    [0] => Array
        (
            [id] => 1
            [first name] => John
            [last name] => Doe
            [email] => john.doe@example.com
        )
    [1] => Array
        (
            [id] => 2
            [first name] => Jane
            [last name] => Smith
            [email] => jane.smith@example.com
        )
    ...
)
*/

This approach makes it very easy to work with the data: $user['email'] is much clearer than $user[3].

Final Thoughts

Reading data from Excel files in PHP is no longer a complicated hassle. Thanks to the powerful PhpSpreadsheet library and the convenience of Composer, you can abstract away all the complexity of file formats and focus on what you really want to do: work with the data itself. By setting up your environment and using a few simple methods, you can build robust data import features into any application.

For many, the goal after importing data is to visualize it in dashboards and reports. If you find yourself in that spot, spending time writing code to build charts can feel like reinventing the wheel. At Graphed , we automate that entire next step. You can connect sources like Google Sheets or upload files, and then use simple, natural language to instantly create all the dashboards you need without writing a single line of charting code. This allows you to get from raw data to actionable insights in seconds, not hours.

Related Articles