Creating streams from strings in PHP
I’m in the process of writing an API that relies on (file-)streams to be passed around.
There are situations where a string instead needs to be used, and for these purposes the data: stream wrapper is used. Initially I thought it was only possible to encode the actual string in base64, which I didn’t like because of the added footprint.
<?php $string = "I should have really done some laundry tonight."; $stream = fopen('data://text/plain;base64,' . base64_encode($string),'r'); echo stream_get_contents($stream); ?>
Quickly checking out the rfc, it turns out that ‘;base64’ can be omitted to just pass along the raw data, which makes a lot more sense in the context of PHP.
Thankfully, PHP gladly supports it:
<?php $string = "I tried, honestly!"; $stream = fopen('data://text/plain,' . $string,'r'); echo stream_get_contents($stream); ?>
Update June 23th, 2013
Just in case anyone stumbles upon this, I would no longer recommend using the data uri for this purpose.
Since PHP 5.1 we have
php://temp. The former keeps the
entire string into memory, and the latter automatically writes to a file as
soon as the stream exceeds a certain amount of memory.
This is how you use it:
<?php $string = 'Some bad-ass string'; $stream = fopen('php://memory','r+'); fwrite($stream, $string); rewind($stream); echo stream_get_contents($stream);
A bit more info can be found on php.net.