Stream Filter

In php one can use filters with streams.  Sometimes it can become handy.  Let’s say you open a .csv file as a stream, but this file is tab separated.  Your program can can process coma separated csvs, but not tab separated.  This is a good use case for a stream filter, because it can make replacements on the fly.  Below is the code that shows how to create and use filter that replaces tabs with comas in the stream.

<?php
class TabFilter extends PHP_User_Filter
{
    private $_data;
 
    /* Called when the filter is initialized */
    function onCreate( )
    {
        $this->_data = '';
        return true;
    }
 
    /* This is where the actual stream data conversion takes place */
    public function filter($in, $out, &$consumed, $closing)
    {
 
        /* We read all the stream data and store it in 
           the '$_data' variable 
        */
        while($bucket = stream_bucket_make_writeable($in))
        {
            $this->_data .= $bucket->data;
            $this->bucket = $bucket;
            $consumed = 0;
        }
 
        /* Now that we have read all the data from the stream we process 
          it and save it again to the bucket.
        */
        if($closing)
        {
            $consumed += strlen($this->_data);
 
            $pattern = "/\t/";
            $str = preg_replace($pattern,
                                ",",
                                $this->_data);
 
            $this->bucket->data = $str;
            $this->bucket->datalen = strlen($this->_data);
 
            if(!empty($this->bucket->data)) {
                stream_bucket_append($out, $this->bucket);
            }
 
            return PSFS_PASS_ON;
        }
 
        return PSFS_FEED_ME;
    }
}
 
stream_filter_register('myFilter', 'URLFilter');
$handle = fopen("http://website.com/tab-delimited-csv", "r");
stream_filter_append($handle, "myFilter");
Share this article

Similar Posts