0

Example Code:

<?php

set_time_limit(0);
$authorization = ""; // OAuth authorization credentials
$fp = fsockopen("ssl://userstream.twitter.com", 443);
$headers = array(
    "GET /1.1/user HTTP/1.1",
    "Host: userstream.twitter.com",
    "Accept-Encoding: deflate, gzip",
    "Authorization: OAuth {$authorization}",
    "",
    "",
);
fwrite($fp, implode("\r\n", $headers));
while (!feof($fp)) {
    if (!$size = hexdec(fgets($fp))) {
        break;
    }
    echo DECODE_FUNCTION(fread($fp, $size));
    fgets($fp); // SKIP CRLF
}

This example works if I implement DECODE_FUNCTION as:

function DECODE_FUNCTION($str) {
    $filename = stream_get_meta_data($fp = tmpfile())['uri'];
    fwrite($fp, $str);
    ob_start();
    readgzfile($filename);
    return ob_get_clean();
}

However, these cases fails:

function DECODE_FUNCTION($str) {
    return gzuncompress($str);
}

or

function DECODE_FUNCTION($str) {
    return gzinflate($str);
}

or

function DECODE_FUNCTION($str) {
    return gzdecode($str);
}

Creating temporary files seems to have much overheads. What is the best way?

Thank you.

mpyw
  • 5,526
  • 4
  • 30
  • 36
  • 1
    Why don't you use `curl`? I'll bet it handles this automatically. – Barmar Feb 01 '14 at 03:39
  • Factually, I need to read multiple **asyncronized** connections in single thread. cURL cannot solve this problem... – mpyw Feb 01 '14 at 03:41
  • Can you do it with `multicurl`? – Barmar Feb 01 '14 at 03:42
  • If you insist on doing it manually, you need to read the `Content-Encoding` header to find out if it's `deflate` or `gzip`. – Barmar Feb 01 '14 at 03:43
  • I confirmed that all responses had `Content-Encoding: gzip`. – mpyw Feb 01 '14 at 03:45
  • I just noticed that you're trying to call the decode function within the loop, that's not right. You have to read and concatenate all the chunks, then call the decoding function on the entire result. – Barmar Feb 01 '14 at 03:48
  • Streaming API endpoints continue returning responses **semipermanently**. – mpyw Feb 01 '14 at 03:51
  • Umm, in that case you need an uncompressing stream that you can feed data to and read the results from. I'm not sure how to do that in PHP. – Barmar Feb 01 '14 at 04:04
  • Okay, I'll do with `readgzfile()`... Better performance will be earned if I call `tmpfile()` only once and reuse it by calling `rewind()` and `ftruncate()`. – mpyw Feb 01 '14 at 04:18

0 Answers0