Gumbo
Gumbo

Reputation: 655785

How to stream-filtering PHP’s standard output data?

Is it possible to filter the data of PHP’s standard output in a stream-like fashion:

standard output  ⟶  output filter  ⟶  standard output

I’m already aware of ob_start. But I don’t want to process the whole output at once but in a stream-like fashion using php_user_filter or something similar.

Upvotes: 4

Views: 780

Answers (2)

Mark
Mark

Reputation: 1137

If I understand your question correctly, you can use the second argument to ob_start(), $chunk_size for this.

ob_start('my_callback', 1024);

The above example would call my_callback() each time output causes the buffer to reach or exceed one kilobyte. If you're spitting out several kilobytes in separate statements, my_callback() would be triggered several times. This wouldn't be useful if you were outputting several kilobytes as a single string, since at most my_callback() can only be triggered once per output.

Upvotes: 0

mario
mario

Reputation: 145512

I don't quite understand what this is for, but that's no reason not to post an answer.

You can use an ob_start() callback and have it process partial content. All you have to do is set ob_implicit_flush() right after initialising. Now usually the callback is a simple in-out function, but you can make it as complex as desired with:

class ob_callback {
    function __invoke($part, $end_flag_0x04) {
        return "+$part";
        // or map to $stream->filter($in, $out, &$consumed, $closing)
    }
    function __destruct() { /* cleanup */ }
}

ob_start(new ob_callback, 2);
ob_implicit_flush(TRUE);

I'm not sure what a stream-y use would look like. But I think there's no other way to intercept PHP standard output. Note that the implicit flush won't work on CLI.

Upvotes: 5

Related Questions