Skip to content
Alex Kiesel edited this page May 26, 2012 · 7 revisions

I/O: Streams

[ [doc://topics/io I/O Basics] | [doc://topics/iocollections Collections] | [doc://topics/streams Streams] ]

Input

Input streams are defined by the [class://io.streams.InputStream InputStream] interface and provide methods for reading.

$stream= ...;

while ($stream->available()) { $chunk= $stream->read(); // ... }

$stream->close();

Input stream implementations are [class://io.streams.FileInputStream FileInputStream] and [class://io.streams.MemoryInputStream MemoryInputStream].

Output

Input streams are defined by the [class://io.streams.OutputStream OutputStream] interface and provide methods for writing.

$stream= ...;

$stream->write($chunk1); $stream->write($chunk2);

$stream->close();

Output stream implementations are [class://io.streams.MemoryOutputStream MemoryOutputStream], [class://io.streams.FileOutputStream FileOutputStream] and [class://io.streams.ConsoleOutputStream ConsoleOutputStream].

Buffered streams

Stream aggregates that support buffering are [class://io.streams.BufferedInputStream BufferedInputStream] and [class://io.streams.BufferedInputStream BufferedOutputStream].

$stream= new BufferedInputStream(new FileInputStream(...)); while ($stream->available()) { $chunk= $stream->read(); // ... } $stream->close();

Seeking

Streams that supporting seeking implement the [class://io.streams.Seekable Seekable] interface.

Stream adapters

The [class://io.streams.Streams Streams] class provides static methods to wrap stream objects into PHP file handles. This way, legacy APIs can be made to work with streams.

// Reading $fi= Streams::readableFd(new MemoryInputStream('Hello')); $hello= fgets($fi, 1024); fclose($fi);

// Writing $fd= Streams::writeableFd(new FileOutputStream(new File('out'))); fwrite($fd, 'Contents'); fclose($fd);

History

The streams API was first introduced in [rfc://0088 RFC 0088 - Streams API] in November 2006.

Clone this wiki locally