PHP’s streams provide a file-like interface for reading and writing data. A single interface for many different data sources lets you write reusable code: a program that extracts data from a local file can just as easily extract data from a web page, and new streams data sources can immediately be used with any existing streams code. This reuse makes streams a powerful and underused feature in PHP.
Streams were a late addition to PHP 4, arriving only in PHP 4.3. As a
result, they’re barely covered in other PHP books,
and hardly anyone uses them to their full extent. Therefore, while
PHP 5 introduces some new streams features, that’s
not the focus of this chapter. Instead, it compares programming with
and without streams and discusses the advantages streams provide over
alternatives, such as
An extension that provides a streams interface to a new data source is called a wrapper. The streams interface consists of 14 methods, but you need only implement the methods that make sense for your data source. For example, if you wanted to provide a streams interface to a mailbox of messages, you might not support renaming or rewriting. You can write wrappers in C or in PHP.
The SimpleXML extension is written to use
the streams interface for its data. This means that the same function
that loads XML from a datafile (
) also loads XML from a URL, an FTP
site, and any other data source you have a wrapper for.
Sometimes, in ...