2013-04-12 186 views
0

我通過API將PHP加載到Google Drive電子表格中。該請求返回XLSX電子表格,我需要將其解壓縮。爲了節省我寫一個臨時的響應,然後調用,例如,zip_open(),有沒有一種方法可以傳遞這樣的方法一個字符串?PHP解壓縮字符串

回答

2

我認爲你最好的選擇是創建一個臨時文件然後解壓縮它。

// Create a temporary file which creates file with unique file name 
$tmp = tempnam(sys_get_temp_dir(), md5(uniqid(microtime(true)))); 

// Write the zipped content inside 
file_put_contents($tmp, $zippedContent); 

// Uncompress and read the ZIP archive 
$zip = new ZipArchive; 
if (true === $zip->open($tmp)) { 
    // Do whatever you want with the archive... 
    // such as $zip->extractTo($dir); $zip->close(); 
} 

// Delete the temporary file 
unlink($tmp); 
+0

恥辱它無法讀取流,哦,這工作:) –

1

我會寫臨時文件自己,但是你可能希望看到的第一個在這裏評論:http://de3.php.net/manual/en/ref.zip.php


wdtemp在seznam點CZ 嗨,如果你的原始內容 ZIP文件在一個字符串,你不能創建文件在你的服務器(因爲安全模式),以便能夠創建一個文件,然後你可以傳遞給zip_open(),你會很難得到 ZIP數據的未壓縮內容。這可能有所幫助:我寫了 簡單的ZIP解壓縮函數,用於從存儲在字符串中的壓縮文件中解壓第一個文件 (不管它是什麼文件)。它是 只是解析第一個文件的本地文件頭,獲取該文件的壓縮數據和該數據的解壓縮(通常, ZIP文件中的數據由'DEFLATE'方法壓縮,所以我們將只是 解壓縮的原始 它通過gzinflate()函數)。

<?php 
function decompress_first_file_from_zip($ZIPContentStr){ 
//Input: ZIP archive - content of entire ZIP archive as a string 
//Output: decompressed content of the first file packed in the ZIP archive 
    //let's parse the ZIP archive 
    //(see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details) 
    //parse 'local file header' for the first file entry in the ZIP archive 
    if(strlen($ZIPContentStr)<102){ 
     //any ZIP file smaller than 102 bytes is invalid 
     printf("error: input data too short<br />\n"); 
     return ''; 
    } 
    $CompressedSize=binstrtonum(substr($ZIPContentStr,18,4)); 
    $UncompressedSize=binstrtonum(substr($ZIPContentStr,22,4)); 
    $FileNameLen=binstrtonum(substr($ZIPContentStr,26,2)); 
    $ExtraFieldLen=binstrtonum(substr($ZIPContentStr,28,2)); 
    $Offs=30+$FileNameLen+$ExtraFieldLen; 
    $ZIPData=substr($ZIPContentStr,$Offs,$CompressedSize); 
    $Data=gzinflate($ZIPData); 
    if(strlen($Data)!=$UncompressedSize){ 
     printf("error: uncompressed data have wrong size<br />\n"); 
     return ''; 
    } 
    else return $Data; 
} 

function binstrtonum($Str){ 
//Returns a number represented in a raw binary data passed as string. 
//This is useful for example when reading integers from a file, 
// when we have the content of the file in a string only. 
//Examples: 
// chr(0xFF) will result as 255 
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535 
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215 
    $Num=0; 
    for($TC1=strlen($Str)-1;$TC1>=0;$TC1--){ //go from most significant byte 
     $Num<<=8; //shift to left by one byte (8 bits) 
     $Num|=ord($Str[$TC1]); //add new byte 
    } 
    return $Num; 
} 
?> 
0

看一看zlib的功能(如果您的系統上)。據我所知有像zlib-decode(左右),這可以處理原始的zip數據。