AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 10.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Antivirus

    • Introduction
    • How to install
    • Setup
    • How to use
    • Scanners

      • Introduction
      • ClamAV
      • Null
      • Custom
    • Events
    • PSR
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
    • Formatting
  • Auth

    • Introduction
    • How to install
    • Fortify

      • Prerequisites
      • Exceptions

        • Failed Login Attempt
        • Password Reset Link Failure
      • Responses

        • Failed Password Reset Link
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • How to use
  • ETags

    • Introduction
    • How to install
    • Setup
    • ETags usage

      • How to use
      • Generators

        • Default Generator
        • Custom Generator
      • Eloquent Models
    • Http Request Preconditions

      • Introduction
      • Resource Context
      • Preconditions
      • Actions
      • RFC 9110

        • If-Match
        • If-Unmodified-Since
        • If-None-Match
        • If-Modified-Since
        • If-Range
      • Extensions

        • Introduction
        • Range
      • Range Validator
      • Download Stream
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Caching
        • Registrar
      • Requests

        • Introduction
        • List Resources
        • List Deleted
        • Show Resource
        • Create Resource
        • Update Resource
        • Delete Resource
        • List Related
        • Process Multiple Resources
        • Helpers
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
        • Remove Response Payload
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Sync
      • Flush
      • Hash
      • MIME-Type
      • Filename
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Env File
    • Aware-of Properties

      • Generator
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Translation

    • Introduction
    • How to install
    • Exporters

      • Introduction
      • Setup
      • How to use
      • Drivers

        • Introduction
        • Array
        • Lang.js (Array)
        • Lang.js (JSON)
        • Cache
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Date Format
      • Semantic Version

Reading

  • Determine if Readable
  • Read
    • Remaining Content
    • All Contents
  • Read Characters
    • Single Character
    • All Characters
  • Read Lines
    • Single Line
    • Single Line Until
    • All Lines
    • All Lines (Using delimiter)
  • Scan Format
    • Scan All
  • Read Chunks
  • Read All using Callback
  • Buffer

Determine if Readable

The isReadable() determines if a stream is readable or not.

$a = FileStream::open('people.txt', 'rb');
$b = FileStream::open('contacts.txt', 'a');

echo $a->isReadable(); // true
echo $b->isReadable(); // false

Read

The read() returns up to the specified amount of bytes requested read. Fewer bytes may be returned, if underlying resource does not contain the amount of bytes requested.

$data = $stream->read(50); // 50 bytes of data

Remaining Content

To obtain the remaining contents of a stream, use the getContents().

$data = $stream
    ->positionAt(50)
    ->getContents();

All Contents

If you wish to obtain the entire contents of a stream, then you can do so by either casting the stream to a string or manually invoking the __toString().

$data = (string) $stream; // All contents of stream

Info

The stream's read/write position is automatically set to 0 (the beginning of the stream), before the content is returned when cast to a string.

Read Characters

Single Character

The readCharacter() method is useful when you wish to read a single character from a stream.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, 'abc');

$stream = FileStream::make($resource)
    ->positionToStart();

// Read a character...
$a = $stream->readCharacter();
$b = $stream->readCharacter();
$c = $stream->readCharacter();

echo $a; // a
echo $b; // b
echo $c; // c

Behind the scene, PHP's fgetc() is used.

All Characters

readAllCharacters() returns an iterable generator which allows you to iterator throughout all the stream's characters.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, 'abc');

$stream = FileStream::make($resource);

// Read all characters...
$buffer = '';
$characters = $stream->readAllCharacters();
foreach ($characters as $character) {
    $buffer .= $character;
}

echo $buffer; // abc

Note

This method automatically rewinds the stream. See readCharacter() as an alternative method.

Read Lines

Single Line

You can use the readLine() method to read a single line of content from the stream.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "a\nb\nc\n");

$stream = FileStream::make($resource)
    ->positionToStart();

// Read a line...
$a = $stream->readLine();
$b = $stream->readLine();
$c = $stream->readLine();

echo trim($a); // a
echo trim($b); // b
echo trim($c); // c

Behind the scene, PHP's fgets() is used.

Note

The readLine() also includes newline character in its output.

Length

The readLine() method also accepts optional $length argument. When length is specified, reading stops when either of these conditions are met.

  • Length - 1 byte (length minus 1 byte) has been reached
  • Newline character is reached (included in output)
  • EOF is reached.
// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "aaa\nbbb\nccc\n");

$stream = FileStream::make($resource)
    ->positionToStart();

// Read length...
echo $stream->readLine(3); // aa (length minus 1 byte)

Single Line Until

Use the readLineUntil() method to read a line until a specified length and or delimiter is reached. This method stops reading when either of the these conditions are met:

  • Length - 1 byte (length minus 1 byte) has been reached
  • Delimiter character is reached (NOT included in output)
  • EOF is reached.
// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "a;b;c;");

$stream = FileStream::make($resource)
    ->positionToStart();

$length = 5;
$delimiter = ';'

// Read until length/delimiter
$a = $stream->readLineUntil($length, $delimiter);
$b = $stream->readLineUntil($length, $delimiter);
$c = $stream->readLineUntil($length, $delimiter);

echo $a; // a
echo $b; // b
echo $c; // c

All Lines

If you need to read all lines from a stream, then use the readAllLines() method. It returns an iterable generator.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "a\nb\nc\n");

$stream = FileStream::make($resource);

// Read all lines...
$buffer = '';
$lines = $stream->readAllLines();
foreach ($lines as $line) {
    $buffer .= $line;
}

echo $buffer; // abc

Note

This method automatically rewinds the stream. See readLine() as an alternative method.

Automatic Trim

Unlike the readLine() method, readAllLines() automatically trims all lines before returning. This means that newline character is NOT included in the output.

Alternative way to read all lines

The Stream and FileStream components inherit from the IteratorAggregate and can therefore be iterated directly. When doing so, it is the equivalent of invoking the readAllLines() method.

// Iterate through stream's lines
foreach ($stream as $line) {
    // ...Do something with line...
}

All Lines (Using delimiter)

You can also iterate though all lines using the readAllUsingDelimiter. It behaves similar to the readLineUntil() method. In the following example, each line is returned when either of these conditions are met:

  • Length - 1 byte (length minus 1 byte) has been reached
  • Delimiter character is reached (NOT included in output)
  • EOF is reached.
// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "aa||bb||cc");

$stream = FileStream::make($resource);

// Read all lines using a length / delimiter
$buffer = '';
$iterator = $stream->readAllUsingDelimiter(10, '||');
foreach ($iterator as $line) {
    $buffer .= $line;
}

echo $buffer; // aabbcc

Note

This method automatically rewinds the stream. See readLineUntil() as an alternative method.

Scan Format

To scan the stream's content according to a format, use the scan() method. It accepts a $format as specified by PHP's fscanf().

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "aa-\nbb-\ncc-\n");

$stream = FileStream::make($resource)
    ->positionToStart();

// Scan according to format
$buffer = '';
while ($scanned = $stream->scan('%s-')) {
    $buffer .= $scanned[0];
}

echo $buffer; // aa-bb-cc-

Note

If the stream you are processing is of considerable size, and you need to scan the entire content, then you should use the readAllUsingFormat() instead of scan().

Scan All

Use readAllUsingFormat() to scan entire stream's content according to specified format.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "aa||\nbb||\ncc||\n");

$stream = FileStream::make($resource);

// Scan according to format
$buffer = '';
$all = $stream->readAllUsingFormat('%s||');
foreach ($all as $scanned) {
    $buffer .= $scanned[0];
}

echo $buffer; // aa||bb||cc||

Note

This method automatically rewinds the stream. See scan() as an alternative method.

Read Chunks

You can also read a stream's content in chunks of a specified size. The readAllInChunks() method accepts an optional $size argument, which determine the amount of bytes to be read per "chunk".

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "abc");

$stream = FileStream::make($resource)
    ->positionToStart();

// Read all in chunks of 1 byte
$buffer = '';
$chunks = $stream->readAllInChunks(1);
foreach ($chunks as $chunk) {
    $buffer .= $chunk;
}

echo $buffer; // abc

Note

This method automatically rewinds the stream. See buffer() as an alternative method.

Read All using Callback

Lastly, if none of the default offered "read all" methods are to your liking, then you can use readAllUsing() method to specify a custom callback for how to read the stream's underlying resource. The method returns an iterable generator, just like the other "read-all" methods.

The given callback will receive the stream's underlying resource as argument.

The following example corresponds to the same result as invoking the readAllInChunks() method.

// Given the following...
$resource = fopen('php://memory', 'r+b');
fwrite($resource, "aabbcc");

$stream = FileStream::make($resource);

// Read all using custom callback
$buffer = '';
$chunks = $stream->readAllUsing(function($resource) {
    return fread($resource, 2);
});

foreach ($chunks as $chunk) {
    $buffer .= $chunk;
}

echo $buffer; // aabbcc

Note

This method automatically rewinds the stream. See buffer() as an alternative method.

Buffer

To read the stream in chunks, using a specific buffer size, use the buffer() method. It accepts the following arguments:

  • int|null $length = null: (optional) Maximum bytes to read from stream. By default, all bytes left are read.
  • int $offset = 0: (optional) The offset on where to start to reading from.
  • int $bufferSize = BufferSizes::BUFFER_8KB: (optional) Read buffer size of each chunk in bytes.
$iterator = $stream->buffer(
    length: 250,
    offset: 22,
    bufferSize: 50
);

foreach ($iterator as $chunk) {
    echo $chunk;
}
Edit page
Last Updated: 26/02/2025, 14:21
Contributors: Alin Eugen Deac, alin
Prev
Seeking
Next
Writing