Skip to content
MNB PHPExcelDeveloper Guide
AI

Getting started

Read Your First XLSX File

Open one worksheet, turn the first row into keys, and process records safely.

Level
Beginner
Reading time
7 min
Package
mnb/mnb-phpexcel
Updated
PHP 8.1+Full packageStreaming
MnbExcel::read()ReadSession::sheet()ReadSession::sheetIfExists()ReadSession::activeSheet()ReadSession::withHeaderRow()ReadSession::rows()

Create a complete runnable script#

read-orders.php
<?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#

CallResponsibility
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#

Safe boundary example
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.