在php中压缩字符串并使用zlib在python中解压缩

2024-09-30 16:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道已经有人问过这个问题:Compress string in php and decompress in python

但没有提供答案(聊天中的讨论已丢失)

我希望PHP客户端压缩一个字符串,将其作为包含在json中的字符串发送到服务器,然后我希望能够对其进行解压缩

我试过zlib:

$ php -a
Interactive shell

php > $msg = "abcdefghijk";
php > $compressed = gzcompress($msg);
php > echo "'".$compressed."'"
php > ;
'x�KLJNIMK�����c'


$ python3
Python 3.7.8 (heads/master-dirty:daa285d, Jul 28 2020, 20:00:50) 
[GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import zlib
>>> comp_msg=r'x�KLJNIMK�����c'
>>> msg = zlib.decompress(comp_msg.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check

。。。但它不起作用。 我猜这是字符串编码的问题,但是使用PHP的mb_convert_编码($compressed,“UTF-8”);这并不能解决问题

我不能问这个问题第一次出现的创造者,因为缺乏声誉。。。 任何帮助都将不胜感激

谢谢


Tags: and字符串答案in编码stringmsgcompress
1条回答
网友
1楼 · 发布于 2024-09-30 16:25:00
  1. 尝试转义字符串常量中的非ASCII字符:
<?php
$msg = "abcdefghijk";
$compressed = gzcompress($msg);
echo "'".addcslashes($compressed, "\x00..\x1F\\\'\"\x7F..\xFF")."'";
// outputs: 'x\234KLJNIMK\317\310\314\312\006\000\031\351\004c'
  1. 尝试在python中对二进制字符串文本使用b前缀:
import zlib
comp_msg=b'x\234KLJNIMK\317\310\314\312\006\000\031\351\004c';
msg = zlib.decompress(comp_msg)
print(msg)
# prints: b`abcdefghijk`

相关问题 更多 >