2013-04-12 184 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数据。