Skip to content
MNB PHPExcelDeveloper Guide
AI

Reading workbooks

Choose the Right Excel Reading Method

Choose a PHP Excel reading method by the result shape you need: streamed rows, arrays, first-row checks, counts, structured summaries, selected columns, or direct cells.

Level
Beginner
Reading time
8 min
Package
mnb/mnb-phpexcel or mnb/mnb-phpexcel-xlsx
Updated
Full packageIndividual XLSXLow memory
Available sincev2.0.3Last API changev2.0.5Version guide
ReadSession::rows()ReadSession::toArray()ReadSession::first()ReadSession::countRows()ReadSession::hasRows()ReadSession::toStructuredSheetArray()ReadSession::cell()
Start with the result

Choose the terminal method from what the application actually needs back.

File size matters, but output shape is the better first question. Avoid materializing rows just because an array is familiar when the workflow only needs a stream, count, first row, or one cell.

Many rowsrows()

Process records incrementally.

Small complete resulttoArray()

Use native PHP array operations.

One record or checkfirst() / hasRows()

Stop as soon as the question is answered.

Known coordinatecell()

Read an exact worksheet location.

Method map

Match the task, return type, and memory behavior before writing the loop.

The terminal call is the contract boundary. After it returns, work with the returned generator, array, scalar, or cell value—not with ReadSession methods.

TaskMethodReturnsMemoryUse when
Process many recordsrows()GeneratorIncremental

Use when the application can handle each row as it arrives.

Work with a complete PHP datasettoArray()arrayRetained

Use for smaller results that genuinely need indexing or PHP array operations.

Inspect only the first recordfirst()?arrayMinimal

Stop as soon as the first normalized data row is available.

Ask whether data existshasRows()boolMinimal

Prefer a Boolean result when existence is the only question.

Count normalized rowscountRows()intStreaming pass

Use when the count itself is the required result.

Read one fixed coordinatecell("B2")mixedTargeted

Use for configuration cells or known workbook positions.

Keep rows plus audit countstoStructuredSheetArray()arrayRetained

Use when source, empty, skipped, header, and returned counts matter together.

Configuration, not execution

selectColumns() narrows the later read; it does not return rows by itself.

Project the fields you need, then finish with rows(), toArray(), first(), or another terminal method.

Common patterns

Prefer the smallest result shape that still solves the job.

Streaming and collection are both valid. The important part is choosing deliberately and keeping the resulting PHP type obvious in the code.

Incremental processing

Stream when records can be handled one at a time.

This avoids retaining the complete returned dataset just to iterate over it.

Stream records
$processed = 0;

foreach ($session->rows() as $row) {
    processRow($row);
    $processed++;
}
In-memory processing

Collect when later logic really needs a native array.

Useful for smaller results that need indexing, sorting, or other array operations.

Collect rows
$rows = $session->toArray();

if ($rows === []) {
    return;
}

$firstEmail = $rows[0]['Email'] ?? null;
Targeted questions

Do not read more data than the question requires.

First-row, existence, count, and direct-cell methods communicate intent better than collecting every row first.

Ask for the smallest result
$first = $session->first();
$hasRows = $session->hasRows();
$count = $session->countRows();
$value = $sheet->cell('B2');
Audit-friendly result

Use structured output when source and returned counts belong together.

This is useful when row normalization and skipped-row accounting are part of the result contract.

Rows plus source counts
$result = $sheet->toStructuredSheetArray([
    'header_row' => 1,
    'skip_empty_rows' => true,
    'row_format' => 'flat',
]);

$rows = $result['rows'];
$counts = $result['summary']['row_counts'];
Empty checks

Test “no data” according to the type the terminal method returns.

There is no universal isEmpty() call after execution. Once a terminal method returns, use the normal PHP check for that returned type.

MethodReturnsEmpty / no-data check
rows()Generator

Track whether the loop yielded, or use hasRows() when a separate existence check is required.

toArray()array

$rows === []

first()?array

$row === null

hasRows()bool

Use the returned Boolean directly.

countRows()int

$count === 0

toStructuredSheetArray()array

$result["rows"] === []

cell()mixed

Use an application-specific null/value check.

Read-pass discipline

Do not stack terminal methods when one pass can answer the workflow.

Calling countRows(), toArray(), and toStructuredSheetArray() in sequence can mean repeated worksheet work. Large-file code should usually gather application counters while processing the primary row stream.

Configure onceChoose one primary terminal methodCalculate application counters during that pass