user1417418
user1417418

Reputation:

Decoding a gzipped string in PHP

I am trying to decode a gzipped body of a REST response (YouTrack-API) with PHP. Nothing seems to work:

I have tried gzinflate, gzdecode and some wild combinations of them including stripping off bytes at the start and end, but without success. I am by no means an expert in compression, so I have no idea if there are even different formats a gzipped string can take, but any old 'online gzip service' can decode the string with no problem at all

Simple example: This string:

H4sIAAAAAAAA//NIzcnJV8jPSVEozy/KSQEARAYhbw8AAAA=

should output:

Hello old world

Put into any online converter I could find, it works, put into any of the PHP functions: data error. What is the deal with PHP and gzip not working at all? has it something to do with either the entire response being gzipped or just the contents?

Upvotes: 2

Views: 7416

Answers (2)

MSE
MSE

Reputation: 685

Here's a complete example:

Gzip Compressing in .NET/C#

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public class Program {
    public static void Main() {
        string s = "Hi!!";

        byte[] byteArray = Encoding.UTF8.GetBytes(s);
        byte[] b2 = Compress(byteArray);

        Console.WriteLine(System.Convert.ToBase64String(b2));
    }

    public static byte[] Compress(byte[] bytes) {
        using (var memoryStream = new MemoryStream()) {
            using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal)) {
                gzipStream.Write(bytes, 0, bytes.Length);
            }
            return memoryStream.ToArray();
        }
    }

    public static byte[] Decompress(byte[] bytes) {
        using (var memoryStream = new MemoryStream(bytes)) {

            using (var outputStream = new MemoryStream()) {
                using (var decompressStream = new GZipStream(memoryStream, CompressionMode.Decompress)) {
                    decompressStream.CopyTo(outputStream);
                }
                return outputStream.ToArray();
            }
        }
    }
}

this code prints the base64 encoded compressed string which is H4sIAAAAAAAEAPPIVFQEANxaFPgEAAAA for the Hi!! input.

Now - here's the code for decompressing in PHP:

echo gzdecode(base64_decode('H4sIAAAAAAAEAPPIVFQEANxaFPgEAAAA'));

Upvotes: 0

Gordon
Gordon

Reputation: 316969

The gzipped string is base64 encoded, so you need to do:

echo gzdecode(base64_decode('H4sIAAAAAAAA//NIzcnJV8jPSVEozy/KSQEARAYhbw8AAAA='));

Upvotes: 6

Related Questions