json_encode with zlib data (gzip, etc) not working

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rca123
Forum Newbie
Posts: 1
Joined: Wed Feb 11, 2009 12:19 pm

json_encode with zlib data (gzip, etc) not working

Post by rca123 »

json_encode doesn't seem to handle zlib encoded data from gzcompress, gzencode, and gzdeflate. It does seem to work with bzcompress data. serialize works. I have included some ways to reproduce the problem below. Same results with version 5.2.0-8+etch10 and 5.2.6-2ubuntu4. Is there something I am missing here or should I submit a bug report?

Code: Select all

php > echo phpversion();
5.2.6-2ubuntu4
php > echo json_encode(array('test'=>'hello there'));
{"test":"hello there"}
php > echo gzcompress(json_encode(array('test'=>'hello there')));
x??V*I-.Q?R?H???W(?H-JU?XA
[b]php > echo json_encode(array("gz"=>gzcompress(json_encode(array('test'=>'hello there')))));[/b]
[b]{"gz":"x"}[/b]
php > echo serialize(array("gz"=>gzcompress(json_encode(array('test'=>'hello there')))));
a:1:{s:2:"gz";s:30:"x??V*I-.Q?R?H???W(?H-JU?XA?";}
php > echo json_encode(array("bz"=>bzcompress(json_encode(array('test'=>'hello there')))));
{"bz":"BZh41AY&SY"}
php > echo gzencode(json_encode(array('test'=>'hello there')));
?V*I-.Q?R?H???W(?H-JU????
php > echo json_encode(array("gz"=>gzencode(json_encode(array('test'=>'hello there')))));
{"gz":"\u001f"}
php > echo gzdeflate(json_encode(array('test'=>'hello there')));
?V*I-.Q?R?H???W(?H-JU?
php > echo json_encode(array("gzdeflate"=>gzdeflate(json_encode(array('test'=>'hello there')))));
{"gzdeflate":""}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: json_encode with zlib data (gzip, etc) not working

Post by Weirdan »

Json string may not contain arbitrary binary data (see http://json.org for what it may contain). Therefor compliant generator is not required to be able to encode data such as binary streams produced by compression algorithms. You best option, I guess, is to encode binary string into base64 before passing it to json_encode().
Post Reply