views:

110

answers:

1

Ok, so there is this PHP implementation of Last.FM API some guy wrote and I'm using it for a small project of mine. His implementation doesn't request gzipped data from Last.FM servers so I decided to modify his implementation to work with gzip to reduce bandwidth. I have no problem in requesting gzipped data, that works just fine and all the data comes compressed (checked). The problem is decoding it. I'm pretty new with PHP and I was trying to decode it for the last two days but nothing I tried worked. :D

Here is the function that asks for and receives the data. If anyone could please help me make this function decode the data I'd be really grateful.

function send ($msg) {
    // Send message over connection
    fwrite($this->handle, $msg);

    $response = array();
    $line_num = 0;
    while ( !feof($this->handle) ) {
        $response[$line_num] =  fgets($this->handle, 4096);
        $line_num++;
    }

    // Return response as array
    return $response;
}

where $this->handle is

    $this->handle = fsockopen($this->host, $this->port, $this->error_number, $this->error_string);

Thank you =)

A: 

Have you tried something like...


$response='';
while(!feof($this->handle)) {
  $response.=fgets($this->handle, 4096);
}
$response=gzdecode($response);
return explode("\n",$response);

Im assuming that the whole response is gzipped and not each line individually. If it's each line you just need to change fgets() into gzdecode(fgets())..

vlad b.
This is valid, with two caveats – gzdecode is trunk only and it unnecessarily puts the whole response in memory before decoding it. The second problem is not so bad, but the first...
Artefacto
You can use something like `gzinflate(substr($data,10,-8))` instead of `gzdecode($data)`, but the indexes may be off because the size of the headers of the data is variable.
Artefacto
I have previously tried using gzdecode() and I get "Fatal error: Call to undefined function gzdecode()". After google-ing it I found out gzdecode() will be implemented in php6? (on localhost I have 5.3.0 installed). I also tried using this simple function I found here - http://php.net/manual/en/function.gzdecode.php but it also does not get the job done...
pootzko
@poo See my comment.
Artefacto
gzinflate (and also gzuncompress) function gives me "Warning: gzinflate() [function.gzinflate]: data error"
pootzko
Artefacto's second followup is the reason - the gz functions do not work on chunks of data - only the whole data stream. If this were a file you could use gzopen(...); while(!gzeof()) { gzread(...); } gzclose(); but from http://php.net/manual/en/filters.compression.php : "they do not provide a means for generalized compression over network streams". Suggest you write it to a local file and use gzopen (the local file may be a filesystem socket though)
symcbean