Is there any way to shorten the string size type zipar
it and then deszipar
equal to the base64 function does?
Is there any way to shorten the string size type zipar
it and then deszipar
equal to the base64 function does?
You have at least two alternatives to compress:
This function compresses the string using the ZLIB data format.
Unzip with gzuncompress()
.
This function compresses the string using the DEFLATE data format.
Unzip with gzinflate()
.
A simple test reveals that gzdeflate
can get better results:
$tring = "Bubu votou para fechar!";
$compressed1 = gzcompress($tring, 9);
echo strlen($compressed1).PHP_EOL; // 31 bytes
$compressed2 = gzdeflate($tring, 9);
echo strlen($compressed2).PHP_EOL; // 25 bytes
See test on Ideone .
The improvement of results obtained in such a simple string is related to the fact that the gzcompress()
function adds a 2-byte header and a 4-byte check value at the end:
In terms of compression, both have the same performance, but in terms of decompression, especially with large data, the gzinflate()
function is faster, its work done almost half the time when compared to gzuncompress()
.
In short:
If the data to be compressed is to stay on the same machine, gzdeflate()
seems to be the ideal option.
In terms of portability, the solution may go through a third function.
To compress a string on a machine and decompress it on a different machine, it is convenient to have some information about the work done:
This function returns a compressed version of the input data compatible with the output of the gzip program.
That is, the output of the function contains the headers and data structure, giving us a way to "safely" move the compressed string .
Unzip with gzdecode()
.
A simple test reveals an increase in the size of the output due to the control information present in it (headers and data structure):
$tring = "Bubu votou para fechar!";
$compressed3 = gzencode($tring, 9);
echo strlen($compressed3).PHP_EOL; // 43 bytes
See test on Ideone .
Maybe this is what you're looking for:
Function gzcompress : used to compress a string, returning another string with compressed content .
Function gzuncompress : used to decompress a compressed string. Returning the original string.
$compressed = gzcompress('Compress me', 9);
$decompress = gzuncompress($compressed);
echo $compressed."\n";
echo $decompress;
Output:
x�s��-(J-.V�M��?
Compress me
Note: The compressed output is larger than the original because the algorithm adds additional information to the compressed string so that it can decompress later. The higher the original string, the better the result.