Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

The SplFileObject class

Reference for PHP SplFileObject: iterate over lines with foreach, flags like DROP_NEW_LINE and READ_CSV, seek to a line, write and truncate files.

SplFileObject is the object-oriented way to work with a file. It wraps a file handle in a class that implements Iterator and SeekableIterator, so you can loop over a file with foreach, jump to a line number with seek(), and read or write with methods instead of free functions.

Its biggest strength is that a file becomes an iterator that reads one line at a time. A multi-gigabyte log can be processed with constant memory, and the object plugs into other SPL tools such as LimitIterator.

PHP
<?php
$file = new SplFileObject('data.txt');
foreach ($file as $number => $line) {
    echo $number, ': ', $line;
}

Try it

PHP Iterating lines with flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Writing and reading CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
new SplFileObject(
    string $filename,
    string $mode = "r",
    bool $useIncludePath = false,
    ?resource $context = null
)
Name Description
$filename Path or stream URL to open.
$mode The same modes as fopen() (r, w, a, c+, ...).
$useIncludePath Search include_path for the file.
$context Optional stream context.

Frequently used methods: fgets(), fgetcsv(), fputcsv(), fwrite(), fread(), eof(), seek(), rewind(), current(), key(), ftruncate(), flock(), setFlags(), setCsvControl(), setMaxLineLen().

Flags (combine with |): DROP_NEW_LINE removes the trailing newline, READ_AHEAD reads the next line eagerly, SKIP_EMPTY skips empty lines (with READ_AHEAD), READ_CSV returns each line as an array.

Return value: the constructor returns the object; methods return what their function counterparts return.

Errors / Exceptions: the constructor throws RuntimeException if the file cannot be opened; seek() throws ValueError for a negative line number.

Usage notes

  • A trailing empty line. Without flags, a file ending in a newline yields a last, empty iteration. Use DROP_NEW_LINE | SKIP_EMPTY | READ_AHEAD to avoid it.
  • SKIP_EMPTY needs READ_AHEAD. On its own it does not skip anything reliably.
  • seek() counts lines, not bytes, and starts at 0. Use fseek() for byte positions.
  • Memory friendly. Iterating never loads the whole file. Combine with new LimitIterator($file, 100, 20) for pagination.
  • Closing: there is no close() method. The file is closed when the object is destroyed, so unset($file) or assign null before deleting or renaming it (matters on Windows).
  • CSV defaults: set the escape character explicitly (the '' argument above) to avoid deprecation warnings in PHP 8.4 and later.
  • SplTempFileObject is the in-memory sibling, handy for building CSV output without touching the disk.
  • SplFileInfo parent: the class extends SplFileInfo, so getSize(), getExtension() and getRealPath() are available.