2013-05-30 50 views
0

我使用這個代碼:寫入部分文件,而無需加載到內存中

// write parts of file to file 
file_put_contents($file,file_get_contents($ar, NULL, NULL, $s, $e)); 

寫一個文件的部分到一個新文件。

我怎麼能這樣做,使用stream_copy_to_stream,或者沒有加載文件到內存這樣做的任何其他方法?

+0

如果你的文件,而不是閱讀與'file_get_contents'完整的內容大,你可以手動打開用'fopen'的文件,然後用一塊'複製fread'和'fwrite'。如果您的文件位於本地目錄中,則還可以使用基本命令'copy'複製。 – MatRt

回答

2

如果您在php.net上進行了一些搜索,您可以輕鬆找到一個能夠滿足您需求的示例。你還可以使用我的建議對你的問題發表評論。

<?php 

$src = fopen('http://www.example.com', 'r'); 
$dest1 = fopen('first1k.txt', 'w'); 
$dest2 = fopen('remainder.txt', 'w'); 

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n"; 
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n"; 

?> 

但是,根據你的PHP版本,這似乎是一個相當大的記憶豬。 然後用fopenfreadfwrite的方式可以

<?php 

    function customCopy($in, $out) 
    { 
     $size = 0; 

     while (!feof($in)) 
      $size += fwrite($out, fread($in,8192)); 

     return $size; 
    } 

?> 

假設$in$out是文件處理程序資源。

1

你可以做類似

$fp = fopen($ar, "r"); 
    $out = fopen($file, "wb"); 
    fseek($fp, $se); 
    while ($data = fread($fp, 2000)){ 
     fwrite($out, $data); 
    } 
    fclose($out); 
    fclose($fp); 
相關問題