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.

  1. <?php
  2.  
  3. $string = "I should have really done some laundry tonight.";
  4.  
  5. $stream = fopen('data://text/plain;base64,' . base64_encode($string),'r');
  6.  
  7. echo stream_get_contents($stream);
  8.  
  9. ?>

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:

  1. <?php
  2.  
  3. $string = "I tried, honestly!";
  4.  
  5. $stream = fopen('data://text/plain,' . $string,'r');
  6.  
  7. echo stream_get_contents($stream);
  8.  
  9. ?>


3 Responses to Creating streams from strings in PHP

  1. 900 Josh 2009-01-30 2:57 pm

    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.

  2. 901 Michael Gauthier 2009-01-30 4:47 pm

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

  3. 902 ellisgl 2009-02-03 1:24 pm

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

Leave a Reply



About

My name is Evert, and I've been writing semi-regularly on this blog since 2006.

I'm currently available for contract work.

more info.

Subscribe

Dropbox

Dropbox is a simple cross-platform online backup and sync application. The first 2GB of space is free, and both you and me get an extra 250MB extra space if you sign up through this link.