Docs Menu

Docs HomePHP Library Manual

MongoDB\GridFS\Bucket::downloadToStream()

On this page

  • Definition
  • Parameters
  • Errors/Exceptions
  • Examples
  • See Also
MongoDB\GridFS\Bucket::downloadToStream()

Selects a GridFS file by its _id and copies its contents to a writable stream.

function downloadToStream($id, $destination): void
$id : mixed
The _id of the file to download.
$destination : resource
Writable stream, to which the GridFS file's contents will be written.

MongoDB\GridFS\Exception\FileNotFoundException if no file was found for the selection criteria.

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

<?php
$bucket = (new MongoDB\Client)->test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$id = $bucket->uploadFromStream('filename', $stream);
$destination = fopen('php://temp', 'w+b');
$bucket->downloadToStream($id, $destination);
var_dump(stream_get_contents($destination, -1, 0));

The output would then resemble:

string(6) "foobar"
←  MongoDB\GridFS\Bucket::delete()MongoDB\GridFS\Bucket::downloadToStreamByName() →