't Bijstere spoor

't Bijstere spoor

A blog about Web development

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);

?>

Comments

Josh
Josh said on Friday, 30 January 2009 at 3:57 pm CET

My favorite usage of the data: wrapper is for raw uploaded csv data. If you let user's cut-n-paste a csv for upload you can use the data: wrapper to fopen the POST data then fgetcsv() on it to save yourself from parsing it manually.

Michael Gauthier
Michael Gauthier said on Friday, 30 January 2009 at 5:47 pm CET

Great tip, thanks! I might use this to simplify some code I have that works with either IPC pipes or strings.

ellisgl
ellisgl said on Tuesday, 3 February 2009 at 2:24 pm CET

@Josh: Thanks for an awesome example of how to use it.

Adidas outlet
Adidas outlet said on Tuesday, 19 January 2010 at 3:35 pm CET

very informative thank you.







Solve this simple math problem to prevent bots from spamming this blog:
6 + 7 =