将zlib.decompress从Python转换为PHP
我想把一段Python代码转换成PHP。
我遇到的问题是这行代码(Python):
zlib.decompress( $gzipped, 16 + zlib.MAX_WBITS );
我不知道PHP里怎么表示zlib.MAX_WBITS。
我在PHP里的代码是:
$response = gzuncompress( $gzipped, ??? );
1 个回答
1
根据反馈进行了编辑的回答
这有点麻烦,但你可以使用 PHP 的 压缩过滤器 来实现。
$params = array('window' => 31);
$fp = fopen('your_data', 'rb');
stream_filter_append($fp, 'zlib.inflate', STREAM_FILTER_READ, $params);
print fread($fp, 1024);
唯一的问题是你需要从一个流中获取压缩的数据……我对 PHP 不太熟悉,所以这个部分就留给你自己去解决了。
下面是针对 PHP 版本 >= 5.4.0 的原始回答
简短回答:试试 gzdecode()
或 zlib_decode()
,而不是 gzuncompress()
。
详细回答……
在 Python 中(Python 3):
>>> print(zlib.decompress.__doc__)
decompress(string[, wbits[, bufsize]]) -- Return decompressed string.
Optional arg wbits is the window buffer size. Optional arg bufsize is
the initial output buffer size.
>>> print(zlib.MAX_WBITS)
15
>>> print(16 + zlib.MAX_WBITS)
31
这意味着数据最初是使用 31 的窗口大小进行压缩的。在 PHP 中,大多数 zlib 函数的默认窗口大小是 15,因此 gzuncompress()
和 gzinflate()
会失败。不过,似乎 gzdecode()
和 zlib_decode()
是可以工作的(我其实也不知道 为什么):
使用 Python3 进行压缩
>>> import zlib
>>> compressor = zlib.compressobj(wbits=(16+zlib.MAX_WBITS))
>>> compressed = compressor.compress(b'Here is a test string compressed by Python with a window size of 31\n')
>>> compressed += compressor.flush()
>>> compressed
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\r\xca\xb1\r\x800\x0c\x04\xc0\x9e)~\x05\xc4\x12\x94\xac\x00\xe4!.\x12#\xdb\x92\x15\xa6\x87\xabo\xa5\x11\xe2\xd8\x11\xf4\x80\x87I\xbfqj{\x8c\xee,8\x06\xb6\x11U;R\xa2\xfe/\xa5\x17M\xb8\xbc\x84^X\xe6\xe9\x03\xabEV\xdbD\x00\x00\x00'
>>> open('/tmp/compressed', 'wb').write(compressed)
85
使用 PHP 进行解压
php > $compressed = file_get_contents('/tmp/compressed');
php > print gzuncompress($compressed);
PHP Warning: gzuncompress(): data error in php shell code on line 1
php > print gzinflate($compressed);
PHP Warning: gzinflate(): data error in php shell code on line 1
php > print gzdecode($compressed);
Here is a test string compressed by Python with a window size of 31
php > print zlib_decode($compressed);
Here is a test string compressed by Python with a window size of 31