1

我正在通过 API 将 Google Drive 电子表格加载到 PHP 中。该请求返回XLSX电子表格,我需要将其解压缩。为了节省我将响应写入临时然后调用,说,zip_open()有没有办法可以将这样的方法传递给字符串?

4

3 回答 3

5

我认为您最好的选择是创建一个临时文件,然后将其解压缩。

// 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);
于 2013-04-12T08:55:48.470 回答
1

我会自己写临时文件,但你可能想在这里看到第一条评论:http: //de3.php.net/manual/en/ref.zip.php


wdtemp at seznam dot 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;
}
?> 
于 2013-04-12T08:49:31.370 回答
0

查看 zlib 函数(如果在您的系统上可用)。据我所知,有类似zlib-decode(或类似)的东西可以处理原始 zip 数据。

于 2013-04-12T08:51:57.987 回答