Read Your First XLSX File
Open one worksheet, turn the first row into keys, and process records safely.
Updated
PHP 8.1+Full packageStreaming
MnbExcel::read()ReadSession::sheet()ReadSession::sheetIfExists()ReadSession::activeSheet()ReadSession::withHeaderRow()ReadSession::rows()What you will learn
- Read a named worksheet as associative rows.
- Handle a missing worksheet or unreadable file.
- Understand when rows are generated rather than buffered.
Before you start
- Complete Installation.
- Place a workbook at
storage/imports/orders.xlsx.
Create a complete runnable script#
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Mnb\PHPExcel\MnbExcel;
foreach (MnbExcel::read(__DIR__ . '/storage/imports/orders.xlsx')
->sheet('Orders')
->withHeaderRow(1)
->rows() as $row) {
printf("%s: %s\n", $row['Order ID'], $row['Customer']);
}Understand the call chain#
| Call | Responsibility |
|---|---|
MnbExcel::read($path) | Detects the file format and returns a unified read session. |
sheet('Orders') | Selects one worksheet by its visible name. |
withHeaderRow(1) | Uses physical row 1 as associative-array keys. |
rows() | Returns a generator that yields one normalized record at a time. |
Add production-safe error handling#
use Mnb\PHPExcel\MnbExcel;
use Mnb\PHPExcel\Support\MnbExcelException;
try {
$workbook = MnbExcel::read($path);
$session = ($workbook->sheetIfExists('Orders') ?? $workbook->activeSheet())
->withHeaderRow(1)
->assertHasRows();
foreach ($session->rows() as $row) {
// Process the record.
}
} catch (MnbExcelException $error) {
error_log(json_encode($error->toErrorArray(debug: true)));
http_response_code(422);
echo 'The workbook could not be processed.';
}Next step#
Continue to Sheets and headers when workbook layouts are inconsistent, or Choose a large-file strategy before importing very large data sets.
Was this guide useful?Use GitHub issues for corrections, missing examples, or unclear behavior.
Open an issue