如何使用 PHP 提取或解壓縮 gzip 檔案?


可以使用 PHP 的 gzread 函式解壓縮壓縮檔案。以下為相同內容的程式碼示例 −

示例

$file_name = name_of/.dump.gz';
$buffer_size = 4096; // The number of bytes that needs to be read at a specific time, 4KB here
$out_file_name = str_replace('.gz', '', $file_name);
$file = gzopen($file_name, 'rb'); //Opening the file in binary mode
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while (!gzeof($file)) {
   fwrite($out_file, gzread($file, $buffer_size)); //Read buffer-size bytes.
}
fclose($out_file); //Close the files once they are done with
gzclose($file);

輸出

這將產生以下輸出−

The uncompressed data which is extracted by unzipping the zipped file.

壓縮檔案的路徑儲存在名為“file_name”的變數中。一次需要讀取的位元組數固定,並分配給名為“buffer_size”的變數。輸出檔案將不具有 .gz 副檔名,因此輸出檔名儲存在名為“out_file_name”的變數中。

“out_file_name”以寫入二進位制模式開啟,以便在從解壓的 zip 檔案中讀取後將內容追加到其中。“file_name”以讀取模式開啟,並使用“gzread”函式讀取內容,並將提取的這些內容寫入“out_file”中。while 迴圈用於確保在檔案末尾讀取內容。

更新於:09-Apr-2020

987 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.