开发者

How to implement mysql compress() function in php

开发者 https://www.devze.com 2022-12-18 12:30 出处:网络
I want to compress TEXT for storing in MySQL. So I would just do gzcompress() in php and then send to mysql, but I am also setting up Sphinx full text search, and it would be nice if it can populate i

I want to compress TEXT for storing in MySQL. So I would just do gzcompress() in php and then send to mysql, but I am also setting up Sphinx full text search, and it would be nice if it can populate its index with a simple query i.e.

select uncompress(thing) from table

However I would still like to do compression and decompression for the application in php rather than mysql, and only use the mysql uncompress() function for sphinx indexing.

The mysql documentation says the following about its compress function:

Nonempty strings are stored as a four-byte length of the uncompressed string (low byte first), followed 开发者_如何学编程by the compressed string.

So my question is... how do I construct this four-byte length of the uncompressed string? After that, the compressed BLOB looks just like the results of the php gzcompress() function.


haven't ever done this, but here are some thoughts:

1) find the length of the uncompressed string... strlen() function ought to work

2) compress the string... you've already done this part

3) pack both together for storage in mysql, formatting the number as mysql wants it:

php's pack function: sounds like you need to use format value "V" for the length (unsigned long... 32 bit, little endian byte order)


Here is my code for that scenario, for uncompress you can also use PHP an djust substr the first 4 bytes away.
Output of mysql:

mysql : "select hex(compress('1234512345'))"
0A000000789C3334323631350411000AEB01FF

The php equivalent:

$string="1234512345";
$data=gzcompress($string);
$len=mb_strlen($string);
$head=pack('V',$len);

echo($head);
echo($data);

Output of PHP:

php test.php  | hexdump -C
00000000  0a 00 00 00 78 9c 33 34  32 36 31 35 04 11 00 0a
0

精彩评论

暂无评论...
验证码 换一张
取 消