简体   繁体   English

遍历结果MongoDB和GridFS(PHP)

[英]Iterating through results MongoDB & GridFS (PHP)

I am using GridFS and I have currently got it to display a single image using findOne, although I would like it to iterate through all the results in the grid and echo them all to screen, here is the code I am using: 我正在使用GridFS,虽然我希望它可以遍历网格中的所有结果并将它们全部回显到屏幕,但是我现在已经使用findOne来显示单个图像,这是我正在使用的代码:

<?php
try {
  // open connection to MongoDB server
  $conn = new Mongo;

  // access database
  $db = $conn->database;

  // get GridFS files collection
  $grid = $db->getGridFS();

  // retrieve file from collection
  header('Content-type: image/png');
  $file = $grid->findOne(array('_id' => new MongoId('4fb437dbee3c471b1f000001')));

  // send headers and file data

  echo $file->getBytes();
  exit;  

  // disconnect from server
  $conn->close();
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());
}
?>

Thanks 谢谢

Use "find" vs "findOne", which will return a result set you can loop through with a foreach, like: 使用“ find”和“ findOne”,这将返回一个结果集,您可以使用foreach对其进行遍历,例如:

$files = $grid->find({}); $ files = $ grid-> find({});

foreach($files as $file) { echo $file->someData; foreach($ files as $ file){echo $ file-> someData; } }

通常,如果要在网页上显示图像,则希望具有一堆标签,例如<img src="someUrl" /> ,然后使每个someUrl句柄获取单个图像。

You set the header to image/png so the browser expects only one image. 您将标头设置为image / png,因此浏览器只需要一张图像。

What you could do is change that to a text/html document and embed the images using the data URI scheme (see http://en.wikipedia.org/wiki/Data_URI_scheme ) and then output the images in a series of images tags. 您可以做的是将其更改为text / html文档,并使用数据URI方案嵌入图像(请参阅http://en.wikipedia.org/wiki/Data_URI_scheme ),然后以一系列图像标签输出图像。

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My images</title>
    <head>
    <body>
    <?php
    /* ... db connection/init code ... */

    $files = $grid->find({});

    foreach($files as $file) { 
       $encodedData = base64_encode($file->getBytes());
       echo "<img src=\"data:image/png;base64,{$encodedData}\">";
       echo "<br>";
    }
    ?>
    </body>
</html>

Note that you probably want to detect if the mime type of the image and change accordingly and set alt, width and height attributes using the file's metadata. 请注意,您可能想检测图像的mime类型并进行相应的更改,并使用文件的元数据设置alt,width和height属性。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM