Stream Filtering with SplFileObject

Attention: Les informations de ce billet sont susceptibles d'être obsolètes car vieux de plus 2 ans.
Warning: The information you are reading may be obsolete, this post was published more than 2 years ago.

Since PHP4 days, the language has been able to interact with streams, a resource object that can be read from or written to in a linear fashion. This feature can help us applying filters function on streams while reading from or written to them. This can be interesting if you want, for instance, to compress or decompress, on the fly, a file before or after accessing it.
To apply those filters, the developer must use PHP stream filtering functions stream_filter_* and/or the php meta wrapper php://filter and have access to a PHP file resource. For instance, any resource returned by fopen can be filtered using PHP.

$path = 'path/to/my/file.txt';
$fp = fopen($path, 'r');
$filter1 = stream_filter_append($fp, 'string.toupper');
$filter2 = stream_filter_prepend($fp, 'string.rot13', STREAM_FILTER_READ);
$res = fgets($fp); //the output text is ROT13 and then uppercased
$res = fgets($fp); //the output text is only uppercased

The stream filters can be applied when reading,  writing or on both actions. They can be removed at any given time. This feature is truly powerful. Lire la suite