Skip to content

Instantly share code, notes, and snippets.

@yaroslavche
Last active January 18, 2024 15:06
Show Gist options
  • Save yaroslavche/b541e09d4267f761f17f6368a49b94d3 to your computer and use it in GitHub Desktop.
Save yaroslavche/b541e09d4267f761f17f6368a49b94d3 to your computer and use it in GitHub Desktop.
PHP. Create a stream from a string

If you know the string is small use

$stream = fopen(sprintf('data://text/plain,%s', $string), 'r');
$result = stream_get_contents($stream);

data://

When passing plain string without base64 encoding, do not forget to pass the string through URLENCODE(), because PHP automatically urldecodes all entities inside passed string (and therefore all + get lost, all % entities will be converted to the corresponding characters).

If data is large - better use

$stream = fopen('php://temp', 'r+');
fwrite($stream, $string);
rewind($stream);
$result = stream_get_contents($stream);

Can use php://memory, but to avoid running out of memory php://temp better choise. It only uses a real file above a certain size. Below that it uses RAM. You can use php://temp/maxmemory:4M.

@typoworx-de
Copy link

Awesome right what I was searching for to get out of hazzle for a http-stream response in my php application using http-client request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment