Logan Bailey

Adventures In Web Development

Blog, About, GitHub, and LinkedIn

With PSR-7 almost execlusively using streams, it's almost essential to have an easy way to convert a string into a stream resource. Combing across the internet, I've found Evert's blog post last updated June 23rd, 2013. I've adapted his 3 liner sample code into a simple function:

/**
 * Convert a string into a stream resource
 * 
 * @param string $string The string to convert
 *
 * @return resource A stream resource.
 */
function str_to_stream(string $string) 
{
    $stream = fopen('php://memory','r+');
    fwrite($stream, $string);
    rewind($stream);
    return $stream;
}
Posted In:
php