Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

SplFileObject

SplFileObject is an SPL class that offers an object-oriented interface for reading and writing files. It extends SplFileInfo and implements SeekableIterator, allowing line-by-line iteration over a file with a foreach loop.

SplFileObject supports reading modes r and r+, writing modes w and a, and CSV parsing via the setFlags() method combined with the READ_CSV flag.

It is a convenient alternative to the procedural fopen()/fgets()/fclose() trio when an object-oriented approach is preferred.

<?php

    $file = new SplFileObject('data.txt', 'r');
    $file->setFlags(SplFileObject::DROP_NEW_LINE);

    foreach ($file as $line) {
        echo $line . PHP_EOL;
    }

?>

Documentation

See Also