簡體   English   中英

如何解碼/膨脹分塊的 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

大概是因為分塊格式,我無法誇大它。 在使用十六進制編輯器手動刪除偏移量並讀取 gzip 存檔后,我可以確認數據沒有損壞。 我想知道是否有合適的方法將這個分塊的 gzip 壓縮響應解析為可讀的字符串?

我也許能夠拆分這些偏移量並將數據連接到一個字符串中以調用 gzinflate,但似乎必須有一種更簡單的方法。

縮小響應的適當方法大致如下:

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函數為你做( 固定 ):

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;

}

用戶@user1309276的解決方案真的幫助了我! 從服務器接收到帶有transfer-encoding: chunked標頭。 沒有一種解決方案有幫助。 這個解決方案對我來說就像魔術一樣。 它只是刪除前 10 個字節。

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

要解碼String使用gzinflate ,Zend_Http_Client lib將有助於執行這種常見任務,使用它很簡單,如果需要自己執行,請參考Zend_Http_Response代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM