MNB PHPExcelDeveloper Guide
Use cases

Read Excel Files Safely

Open an Excel workbook, inspect it before reading, select a worksheet safely, stream or collect records, and understand every returned value.

Updated

PHP 8.1+Full packageIndividual XLSXStreaming
LevelBeginnerReading time14 minPackagemnb/mnb-phpexcel or mnb/mnb-phpexcel-xlsx
MnbExcel::read()Xlsx::read()ReadSession::inspect()ReadSession::sheetIfExists()ReadSession::activeSheet()ReadSession::withHeaderRow()ReadSession::rows()

What you will learn

  • Inspect the workbook before reading business records.
  • Select a named sheet with an intentional active-sheet fallback.
  • Choose streaming or array collection based on the job.

Install the correct package#

Terminal
composer require mnb/mnb-phpexcel:^2.0

The full package exposes MnbExcel. The individual package exposes Xlsx. Both create the same read-session API after the workbook is opened.

Open, inspect, select, and stream#

read-workbook.php
use Mnb\PHPExcel\MnbExcel;

$path = __DIR__ . '/storage/imports/orders.xlsx';
$workbook = MnbExcel::read($path);
read-orders.php
$inspection = $workbook->inspect();
$sheetNames = $workbook->sheetNames();

if ($sheetNames === []) {
    throw new RuntimeException('The workbook has no readable worksheets.');
}

$sheet = $workbook->sheetIfExists('Orders')
    ?? $workbook->activeSheet();

$session = $sheet
    ->withHeaderRow(1)
    ->withOptions([
        'skip_empty_rows' => true,
        'max_rows' => 5000,
    ])
    ->assertHasRows();

foreach ($session->rows() as $row) {
    echo $row['Order ID'] . ' — ' . $row['Customer'] . PHP_EOL;
}

Developer contract#

Returns from read()
ReadSession
Returns from rows()
Generator<int, array<string, mixed>>
Reads immediately
read() creates a session; rows() begins row consumption.
Memory behavior
Rows are yielded one at a time when the native streaming path is available.
Empty check
hasRows(), isEmpty(), or assertHasRows() on the session.
Errors
MnbExcelException for library failures; application validation may throw RuntimeException.
ReturnsGenerator<int, array<string, mixed>>ShapeEach yielded row uses header names as keys
Expected output
ORD-1001 — Arjun Stores
ORD-1002 — Northwind Retail

The header row is not yielded as a business record.

Choose how to consume the data#

NeedUseReturn type
Process rows with low memoryrows()Generator
Collect all returned rowstoArray()array
Read only the first data rowfirst()?array
Check for data without collecting ithasRows()bool
Get detailed source and skipped-row countstoStructuredSheetArray()array
Read a fixed XLSX coordinatecell("B2")mixed

Open the complete reading-method decision table →

Common mistake: treating an array like a session#

PHP
$rows = $session->toArray();
$rows->isEmpty();

Review all common mistakes →

Continue the workflow#