將數據從一個流傳輸到另一個流

[英]Pipe data from one stream to another


I am looking for the best way to pipe data from one stream to another without having to deal with buffering myself. Basically the equivalent of the node.js stream.pipe function.

我正在尋找將數據從一個流傳輸到另一個流的最佳方法,而無需自己處理緩沖。基本上相當於node.js stream.pipe函數。

There is stream_copy_to_stream, but according to the comments on the manual page it is quite a memory hog (possibly reading the whole stream into memory?).

有stream_copy_to_stream,但根據手冊頁上的注釋,這是一個非常大的內存(可能將整個流讀入內存?)。

Of course I could do something like this:

當然我可以這樣做:

$fh = fopen('filename.txt', 'rb');
$out = STDOUT;
while (!feof($fh)) {
    $bytes = 1024;
    fwrite(STDOUT, fread($fh, $bytes), $bytes);
}
fclose($fh);

But I'm hoping there is an easier API to accomplish this, without having to do the buffering myself.

但我希望有一個更簡單的API來完成這個,而不必自己做緩沖。

Thanks.

1 个解决方案

#1


3  

I downloaded the source code of PHP 5.4.0 and looked up stream_copy_to_stream (streams.c line 1419). It looks reasonable in my opinion.

我下載了PHP 5.4.0的源代碼並查找了stream_copy_to_stream(streams.c第1419行)。在我看來,它看起來很合理。

First it tries to memory-map the source stream, and write the whole thing to the destination in one go without using an intermediate buffer.

首先,它嘗試對源流進行內存映射,並在不使用中間緩沖區的情況下一次性將整個內容寫入目標。

If memory mapping is not possible, then it uses an internal buffer (8192 bytes, see CHUNK_SIZE in php_streams_int.h line 49) to shuffle the data from the source to the destination.

如果無法進行內存映射,則它使用內部緩沖區(8192字節,請參閱php_streams_int.h第49行中的CHUNK_SIZE)將數據從源緩沖到目標。

Either the manual comment is wrong, or the developers have improved the function since it was first written. I would give it another look.

手動注釋是錯誤的,或者開發人員自首次編寫以來已經改進了該功能。我再試一次。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/12/31/6f2a587ecc8b0a0428f2c94ac056dd14.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com