如何解码/膨胀一个分块的gzip字符串


How to decode/inflate a chunked gzip string?

在PHP中发出gzip deflate请求后,我收到了偏移块中的deflated字符串,看起来像下面的

示例大大缩短以显示格式:

00001B4E
¾”kŒj…Øæ’ìÑ«F1ìÊ`+ƒQì¹UÜjùJƒZ'µy¡ÓUžGr‡J&=KLËÙÍ~=ÍkR
0000102F
ñÞœÞôΑüo[¾”+’Ñ8#à»0±R-4VÕ’n›êˆÍ.MCŽ…ÏÖr¿3M—èßñ°r¡'+
00000000

我无法夸大这一点,大概是因为大块的格式。在用Hex编辑器手动删除偏移量并读取gzip档案后,我可以确认数据没有损坏。我想知道是否有一种合适的方法可以将这个分块的gzip收缩响应解析为可读字符串?

我可能能够拆分这些偏移量,并将数据连接在一个字符串中以调用gzonflate,但似乎必须有一种更简单的方法。

压缩分块响应的正确方法大致如下:

initialise string to hold result
for each chunk {
  check that the stated chunk length equals the string length of the chunk
  append the chunk data to the result variable
}

这里有一个方便的PHP函数可以帮你做到这一点(FIXED):

function unchunk_string ($str) {
  // A string to hold the result
  $result = '';
  // Split input by CRLF
  $parts = explode("'r'n", $str);
  // These vars track the current chunk
  $chunkLen = 0;
  $thisChunk = '';
  // Loop the data
  while (($part = array_shift($parts)) !== NULL) {
    if ($chunkLen) {
      // Add the data to the string
      // Don't forget, the data might contain a literal CRLF
      $thisChunk .= $part."'r'n";
      if (strlen($thisChunk) == $chunkLen) {
        // Chunk is complete
        $result .= $thisChunk;
        $chunkLen = 0;
        $thisChunk = '';
      } else if (strlen($thisChunk) == $chunkLen + 2) {
        // Chunk is complete, remove trailing CRLF
        $result .= substr($thisChunk, 0, -2);
        $chunkLen = 0;
        $thisChunk = '';
      } else if (strlen($thisChunk) > $chunkLen) {
        // Data is malformed
        return FALSE;
      }
    } else {
      // If we are not in a chunk, get length of the new one
      if ($part === '') continue;
      if (!$chunkLen = hexdec($part)) break;
    }
  }
  // Return the decoded data of FALSE if it is incomplete
  return ($chunkLen) ? FALSE : $result;
}

要使用gzinflate解码字符串,Zend_Http_Client lib将有助于完成这类常见任务,使用起来很浪费,如果需要在自己的上执行,请参阅Zend_Http_Response代码

用户@user1309276的解决方案真的帮助了我!从服务器接收到一个带有transfer-encoding: chunked头的gzip压缩json响应。所有的解决方案都无济于事。这个解决方案对我来说就像魔术一样!它只删除前10个字节。

$data = json_decode(gzinflate(substr($response->getContent(), 10)), true);