Open a string as a stream in PHP.

Sometimes a functionality to handle string input the same as file/stream input is quite handy. This is a neat way of having PHP create a stream out of a string. It’s a pitty that this stream is only readable, no writing, appending or stat() is allowed. Nevertheless it’s quite useful to avoid having to duplicate logic or reading a whole file into a buffer instead.

// open a string as a stream
$string = 'Hello World';
$stream = fopen('data://text/plain,' . $string, 'r');

// you can only read of that stream
// but all stream-reading functions are usable
$line = fgets($stream);