2009-06-29 3 views
1

У меня есть php-скрипт, который создает резервную копию моей таблицы в формате .sql, и я хочу сохранить файл в формате gzip с помощью PHP. Как мне это сделать.Сжатие GZIP в PHP

ответ

5

Вы также можете использовать a filter. На странице руководства:

<?php 
$params = array('level' => 6, 'window' => 15, 'memory' => 9); 

$original_text = "You SQL queries here..."; 

$fp = fopen('yourfile.sql.gz', 'w'); 
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params); 
fwrite($fp, $original_text); 
fclose($fp); 
?> 
2

Используйте функции Zlib.

documentation Читать подробности

пример, взятый прямо из связанной страницы:

<?php 

$filename = tempnam('/tmp', 'zlibtest') . '.gz'; 
$s = "Only a test, test, test, test, test, test, test, test!\n"; 

/***** WRITING THE FILE *****/ 
// open file for writing with maximum compression 
$zp = gzopen($filename, "w9"); 

// write string to file 
gzwrite($zp, $s); 

// close file 
gzclose($zp); 

/***** READING IT *****/ 
// open file for reading 
$zp = gzopen($filename, "r"); 

// read 3 char 
echo gzread($zp, 3); 

// output until end of the file and close it. 
gzpassthru($zp); 
gzclose($zp); 


/***** ANOTHER WAY TO READ (and print) IT *****/ 
// open file and print content (the 2nd time). 
if (readgzfile($filename) != strlen($s)) { 
     echo "Error with zlib functions!"; 
} 
?> 

Надежда, что помогает.

2

Вот еще одно решение, которое в основном поднимает Carlos Lima идею:

<?php 
    ob_start(); /* start buffering */ 
    echo "your cvs or sql output!";  
    $content = ob_get_contents(); /* get the buffer */ 
    ob_end_clean(); 
    $content = gzencode($content, 9);  
    header("Content-Type: application/force-download"); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Type: application/download"); 
    header("Content-Description: Download SQL Export"); 
    header('Content-Disposition: attachment; filename=test.txt.gz'); 
    echo $content; 
    die(); 
?>